Java Tutorial/2D Graphics/Rectangle

Материал из Java эксперт
Перейти к: навигация, поиск

Checks, whether the given rectangle1 fully contains rectangle 2 (even if rectangle 2 has a height or width of zero!).

/* 
 * JCommon : a free general purpose class library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
 *
 * Project Info:  http://www.jfree.org/jcommon/index.html
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * -------------------
 * ShapeUtilities.java
 * -------------------
 * (C)opyright 2003-2008, by Object Refinery Limited and Contributors.
 *
 * Original Author:  David Gilbert (for Object Refinery Limited);
 * Contributor(s):   -;
 *
 * $Id: ShapeUtilities.java,v 1.18 2008/06/02 06:58:28 mungady Exp $
 *
 * Changes
 * -------
 * 13-Aug-2003 : Version 1 (DG);
 * 16-Mar-2004 : Moved rotateShape() from RefineryUtilities.java to here (DG);
 * 13-May-2004 : Added new shape creation methods (DG);
 * 30-Sep-2004 : Added createLineRegion() method (DG);
 *               Moved drawRotatedShape() method from RefineryUtilities class
 *               to this class (DG);
 * 04-Oct-2004 : Renamed ShapeUtils --> ShapeUtilities (DG);
 * 26-Oct-2004 : Added a method to test the equality of two Line2D
 *               instances (DG);
 * 10-Nov-2004 : Added new translateShape() and equal(Ellipse2D, Ellipse2D)
 *               methods (DG);
 * 11-Nov-2004 : Renamed translateShape() --> createTranslatedShape() (DG);
 * 07-Jan-2005 : Minor Javadoc fix (DG);
 * 11-Jan-2005 : Removed deprecated code in preparation for 1.0.0 release (DG);
 * 21-Jan-2005 : Modified return type of RectangleAnchor.coordinates()
 *               method (DG);
 * 22-Feb-2005 : Added equality tests for Arc2D and GeneralPath (DG);
 * 16-Mar-2005 : Fixed bug where equal(Shape, Shape) fails for two Polygon
 *               instances (DG);
 * 01-Jun-2008 : Fixed bug in equal(GeneralPath, GeneralPath) method (DG);
 *
 */
import java.awt.Shape;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
/**
 * Utility methods for {@link Shape} objects.
 *
 * @author David Gilbert
 */
public class Main {

  /**
   * Checks, whether the given rectangle1 fully contains rectangle 2
   * (even if rectangle 2 has a height or width of zero!).
   *
   * @param rect1  the first rectangle.
   * @param rect2  the second rectangle.
   *
   * @return A boolean.
   */
  public static boolean contains(final Rectangle2D rect1,
                                 final Rectangle2D rect2) {
      final double x0 = rect1.getX();
      final double y0 = rect1.getY();
      final double x = rect2.getX();
      final double y = rect2.getY();
      final double w = rect2.getWidth();
      final double h = rect2.getHeight();
      return ((x >= x0) && (y >= y0)
              && ((x + w) <= (x0 + rect1.getWidth()))
              && ((y + h) <= (y0 + rect1.getHeight())));
  }
}





Clips the specified line to the given rectangle.

/* 
 * JFreeChart : a free chart library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
 *
 * Project Info:  http://www.jfree.org/jfreechart/index.html
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * ------------------
 * LineUtilities.java
 * ------------------
 * (C) Copyright 2008, by Object Refinery Limited and Contributors.
 *
 * Original Author:  David Gilbert (for Object Refinery Limited);
 * Contributor(s):   -;
 *
 * Changes
 * -------
 * 05-Nov-2008 : Version 1 (DG);
 *
 */

import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
/**
 * Some utility methods for {@link Line2D} objects.
 *
 * @since 1.0.12
 */
public class LineUtilities {
    /**
     * Clips the specified line to the given rectangle.
     *
     * @param line  the line (<code>null</code> not permitted).
     * @param rect  the clipping rectangle (<code>null</code> not permitted).
     *
     * @return <code>true</code> if the clipped line is visible, and
     *     <code>false</code> otherwise.
     */
    public static boolean clipLine(Line2D line, Rectangle2D rect) {
        double x1 = line.getX1();
        double y1 = line.getY1();
        double x2 = line.getX2();
        double y2 = line.getY2();
        double minX = rect.getMinX();
        double maxX = rect.getMaxX();
        double minY = rect.getMinY();
        double maxY = rect.getMaxY();
        int f1 = rect.outcode(x1, y1);
        int f2 = rect.outcode(x2, y2);
        while ((f1 | f2) != 0) {
            if ((f1 & f2) != 0) {
                return false;
            }
            double dx = (x2 - x1);
            double dy = (y2 - y1);
            // update (x1, y1), (x2, y2) and f1 and f2 using intersections
            // then recheck
            if (f1 != 0) {
                // first point is outside, so we update it against one of the
                // four sides then continue
                if ((f1 & Rectangle2D.OUT_LEFT) == Rectangle2D.OUT_LEFT
                        && dx != 0.0) {
                    y1 = y1 + (minX - x1) * dy / dx;
                    x1 = minX;
                }
                else if ((f1 & Rectangle2D.OUT_RIGHT) == Rectangle2D.OUT_RIGHT
                        && dx != 0.0) {
                    y1 = y1 + (maxX - x1) * dy / dx;
                    x1 = maxX;
                }
                else if ((f1 & Rectangle2D.OUT_BOTTOM) == Rectangle2D.OUT_BOTTOM
                        && dy != 0.0) {
                    x1 = x1 + (maxY - y1) * dx / dy;
                    y1 = maxY;
                }
                else if ((f1 & Rectangle2D.OUT_TOP) == Rectangle2D.OUT_TOP
                        && dy != 0.0) {
                    x1 = x1 + (minY - y1) * dx / dy;
                    y1 = minY;
                }
                f1 = rect.outcode(x1, y1);
            }
            else if (f2 != 0) {
                // second point is outside, so we update it against one of the
                // four sides then continue
                if ((f2 & Rectangle2D.OUT_LEFT) == Rectangle2D.OUT_LEFT
                        && dx != 0.0) {
                    y2 = y2 + (minX - x2) * dy / dx;
                    x2 = minX;
                }
                else if ((f2 & Rectangle2D.OUT_RIGHT) == Rectangle2D.OUT_RIGHT
                        && dx != 0.0) {
                    y2 = y2 + (maxX - x2) * dy / dx;
                    x2 = maxX;
                }
                else if ((f2 & Rectangle2D.OUT_BOTTOM) == Rectangle2D.OUT_BOTTOM
                        && dy != 0.0) {
                    x2 = x2 + (maxY - y2) * dx / dy;
                    y2 = maxY;
                }
                else if ((f2 & Rectangle2D.OUT_TOP) == Rectangle2D.OUT_TOP
                        && dy != 0.0) {
                    x2 = x2 + (minY - y2) * dx / dy;
                    y2 = minY;
                }
                f2 = rect.outcode(x2, y2);
            }
        }
        line.setLine(x1, y1, x2, y2);
        return true;  // the line is visible - if it wasn"t, we"d have
                      // returned false from within the while loop above
    }
}





Draw a three-dimensional rectangle outline

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainClass extends JPanel {
  public static void main(String[] a) {
    JFrame f = new JFrame();
    f.setSize(400, 400);
    f.add(new MainClass());
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
  }
  public void paint(Graphics g) {
    g.setColor (Color.yellow);  
    g.draw3DRect (5, 15, 50, 75, false); 
  }
}





Draw Rectangle

import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyCanvas extends JComponent {
  public void paint(Graphics g) {
    g.drawRect (10, 10, 200, 200);  
  }
}
public class DrawRect {
  public static void main(String[] a) {
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setBounds(30, 30, 300, 300);
    window.getContentPane().add(new MyCanvas());
    window.setVisible(true);
  }
}





Draw Rectangle with Rectangle2D.Float

import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
public class MainClass extends Frame {
  public static void main(String[] args) {
    (new MainClass()).setVisible(true);
  }
  public MainClass() {
    setSize(150, 150);
  }
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    Rectangle2D r2d = new Rectangle2D.Float(10f, 10f, 130f, 130f);
    g2d.draw(r2d);
  }
}





drawRect (int, int, int, int) to draw a rectangle outline

import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainClass extends JPanel {
  public static void main(String[] a) {
    JFrame f = new JFrame();
    f.setSize(400, 400);
    f.add(new MainClass());
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
  }
  public void paint(Graphics g) {
    g.drawRect (5, 15, 50, 75); 
  }
}





Draw RoundRectangle2D.Float

import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.RoundRectangle2D;
public class MainClass extends Frame {
  public static void main(String[] args) {
    (new MainClass()).setVisible(true);
  }
  public MainClass() {
    super("Shape Sampler");
    setSize(400, 550);
  }
  public void paint(Graphics g) {
    RoundRectangle2D rrect;
    Graphics2D g2d = (Graphics2D) g;
    rrect = new RoundRectangle2D.Float(50, 50, 100, 200, 30, 20);
    g2d.draw(rrect);
  }
}





drawRoundRect (int, int, int, int, int, int) to draw a rounded rectangle outline

import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainClass extends JPanel {
  public static void main(String[] a) {
    JFrame f = new JFrame();
    f.setSize(400, 400);
    f.add(new MainClass());
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
  }
  public void paint(Graphics g) {
    g.drawRoundRect (5, 15, 50, 75, 20, 15);  
  }
}





Fill 3D Rectangle

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyCanvas extends JComponent {
  public void paint(Graphics g) {
    g.setColor(Color.RED);
    g.fill3DRect(20, 20, 200, 200,true);
  }
}
public class Fill3DRect {
  public static void main(String[] a) {
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setBounds(30, 30, 300, 300);
    window.getContentPane().add(new MyCanvas());
    window.setVisible(true);
  }
}





Grow a rectangle

// This example is from the book _Java AWT Reference_ by John Zukowski.
// Written by John Zukowski.  Copyright (c) 1997 O"Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or
import java.awt.Rectangle;
public class rect {
  public static void main(String[] args) {
    Rectangle r = new Rectangle(100, 100, 200, 200);
    System.out.println(r);
    r.grow(50, 75);
    System.out.println(r);
    r.grow(-25, -50);
    System.out.println(r);
  }
}





How do I...Fill shapes?

import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyCanvas extends JComponent {
  public void paint(Graphics g) {
    g.fillRect(20, 20, 200, 200);
  }
}
public class FillRect {
  public static void main(String[] a) {
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setBounds(30, 30, 300, 300);
    window.getContentPane().add(new MyCanvas());
    window.setVisible(true);
  }
}





Intersection between rectangles

// This example is from the book _Java AWT Reference_ by John Zukowski.
// Written by John Zukowski.  Copyright (c) 1997 O"Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JFrame;
public class intersection extends JFrame {
  Rectangle r = new Rectangle(50, 50, 100, 100);
  Rectangle r1 = new Rectangle(100, 100, 75, 75);
  intersection() {
    super("Intersection");
    setSize(250, 250);
  }
  public void paint(Graphics g) {
    g.drawRect(r.x, r.y, r.width, r.height);
    g.drawRect(r1.x, r1.y, r1.width, r1.height);
    Rectangle r2 = r.intersection(r1);
    System.out.println(r2);
    g.fillRect(r2.x, r2.y, r2.width, r2.height);
  }
  public static void main(String[] args) {
    JFrame f = new intersection();
    f.setVisible(true);
  }
}





java.awt.Rectangle

  1. A Rectange object specifics a rectangular area in the coordinate system.
  2. Its x and y fields specify the top-left corner coordinate.
  3. Its width and height fields specify the width and height of the rectangle, respectively.

Here are some of the constructors of the Rectangle class.



public Rectangle ()
public Rectangle (Dimension d)
public Rectangle (int width, int height)
public Rectangle (int x, int y, int width, int height)



A zero value for a field is assumed if the field is missing from a constructor"s argument list.


Ractangle with rounded corners drawn using Java 2D Graphics API

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.RoundRectangle2D;
public class Main extends javax.swing.JFrame {
    
    public Main() {
      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
      setSize(600,600);
    }
    
    public void paint(Graphics g) {
        Graphics2D graphics2 = (Graphics2D) g;
        RoundRectangle2D roundedRectangle = new RoundRectangle2D.Float(100, 100, 240, 160, 10, 10);
        graphics2.draw(roundedRectangle);
    }
    
    public static void main(String args[]) {
        new Main().setVisible(true);
    }
}





Returns a point based on (x, y) but constrained to be within the bounds of a given rectangle.

/* 
 * JCommon : a free general purpose class library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
 *
 * Project Info:  http://www.jfree.org/jcommon/index.html
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * -------------------
 * ShapeUtilities.java
 * -------------------
 * (C)opyright 2003-2008, by Object Refinery Limited and Contributors.
 *
 * Original Author:  David Gilbert (for Object Refinery Limited);
 * Contributor(s):   -;
 *
 * $Id: ShapeUtilities.java,v 1.18 2008/06/02 06:58:28 mungady Exp $
 *
 * Changes
 * -------
 * 13-Aug-2003 : Version 1 (DG);
 * 16-Mar-2004 : Moved rotateShape() from RefineryUtilities.java to here (DG);
 * 13-May-2004 : Added new shape creation methods (DG);
 * 30-Sep-2004 : Added createLineRegion() method (DG);
 *               Moved drawRotatedShape() method from RefineryUtilities class
 *               to this class (DG);
 * 04-Oct-2004 : Renamed ShapeUtils --> ShapeUtilities (DG);
 * 26-Oct-2004 : Added a method to test the equality of two Line2D
 *               instances (DG);
 * 10-Nov-2004 : Added new translateShape() and equal(Ellipse2D, Ellipse2D)
 *               methods (DG);
 * 11-Nov-2004 : Renamed translateShape() --> createTranslatedShape() (DG);
 * 07-Jan-2005 : Minor Javadoc fix (DG);
 * 11-Jan-2005 : Removed deprecated code in preparation for 1.0.0 release (DG);
 * 21-Jan-2005 : Modified return type of RectangleAnchor.coordinates()
 *               method (DG);
 * 22-Feb-2005 : Added equality tests for Arc2D and GeneralPath (DG);
 * 16-Mar-2005 : Fixed bug where equal(Shape, Shape) fails for two Polygon
 *               instances (DG);
 * 01-Jun-2008 : Fixed bug in equal(GeneralPath, GeneralPath) method (DG);
 *
 */
import java.awt.Shape;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
/**
 * Utility methods for {@link Shape} objects.
 *
 * @author David Gilbert
 */
public class Main {

  /**
   * Returns a point based on (x, y) but constrained to be within the bounds
   * of a given rectangle.
   *
   * @param x  the x-coordinate.
   * @param y  the y-coordinate.
   * @param area  the constraining rectangle (<code>null</code> not
   *              permitted).
   *
   * @return A point within the rectangle.
   *
   * @throws NullPointerException if <code>area</code> is <code>null</code>.
   */
  public static Point2D getPointInRectangle(double x, double y,
                                            final Rectangle2D area) {
      x = Math.max(area.getMinX(), Math.min(x, area.getMaxX()));
      y = Math.max(area.getMinY(), Math.min(y, area.getMaxY()));
      return new Point2D.Double(x, y);
  }
}





Union two Rectangles

// This example is from the book _Java AWT Reference_ by John Zukowski.
// Written by John Zukowski.  Copyright (c) 1997 O"Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JFrame;
public class union extends JFrame {
  Rectangle r = new Rectangle(50, 50, 100, 100);
  Rectangle r1 = new Rectangle(100, 100, 75, 75);
  union() {
    super("Union");
    setSize(250, 250);
  }
  public void paint(Graphics g) {
    g.setColor(Color.lightGray);
    Rectangle r2 = r.union(r1);
    g.fillRect(r2.x, r2.y, r2.width, r2.height);
    g.setColor(Color.black);
    g.drawRect(r.x, r.y, r.width, r.height);
    g.drawRect(r1.x, r1.y, r1.width, r1.height);
  }
  public static void main(String[] args) {
    JFrame f = new union();
    f.setVisible(true);
  }
}