|
|
Displaying Graphics with Graphics2D |
By changing the stroke and paint attributes in theGraphics2Dcontext before rendering, you can easily apply fancy line styles and fill patterns to graphics primitives.For example, to draw a dashed line, you create an appropriate
Strokeobject and callsetStroketo add it to theGraphics2Dcontext before you render the line. Similarly, to apply a gradient fill to aShape, you create aGradientPaintobject and add it to theGraphics2Dcontext by callingsetPaintbefore rendering theShape.The
ShapesDemo2Dapplet introduced in the overview demonstrates how you can render basic geometries using theGraphics2Ddrawandfillmethods. Each of the shapes is constructed from one of the geometries and then rendered throughGraphics2D. TherectHeightandrectWidthvariables define the dimensions of the space where each shape is drawn in, in pixels. The x and y variables change for each shape so that they are drawn in a grid formation:
![]()
// draw Line2D.Double g2.draw(new Line2D.Double(x, y+rectHeight-1, x + rectWidth, y));![]()
// draw Rectangle2D.Double g2.setStroke(stroke); g2.draw(new Rectangle2D.Double(x, y, rectWidth, rectHeight));![]()
// draw RoundRectangle2D.Double g2.setStroke(dashed); g2.draw(new RoundRectangle2D.Double(x, y, rectWidth, rectHeight, 10, 10));![]()
// draw Arc2D.Double g2.setStroke(wideStroke); g2.draw(new Arc2D.Double(x, y, rectWidth, rectHeight, 90, 135, Arc2D.OPEN));![]()
// draw Ellipse2D.Double g2.setStroke(stroke); g2.draw(new Ellipse2D.Double(x, y, rectWidth, rectHeight));![]()
// draw GeneralPath (polygon) int x1Points[] = {x, x+rectWidth, x, x+rectWidth}; int y1Points[] = {y, y+rectHeight, y+rectHeight, y}; GeneralPath polygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD, x1Points.length); polygon.moveTo(x1Points[0], y1Points[0]); for (int index = 1; index < x1Points.length; index++) { polygon.lineTo(x1Points[index], y1Points[index]); }; polygon.closePath(); g2.draw(polygon);![]()
// draw GeneralPath (polyline) int x2Points[] = {x, x+rectWidth, x, x+rectWidth}; int y2Points[] = {y, y+rectHeight, y+rectHeight, y}; GeneralPath polyline = new GeneralPath(GeneralPath.WIND_EVEN_ODD, x2Points.length); polyline.moveTo (x2Points[0], y2Points[0]); for (int index = 1; index < x2Points.length; index++) { polyline.lineTo(x2Points[index], y2Points[index]); }; g2.draw(polyline);![]()
// fill Rectangle2D.Double (red) g2.setPaint(red); g2.fill(new Rectangle2D.Double(x, y, rectWidth, rectHeight));![]()
// fill RoundRectangle2D.Double g2.setPaint(redtowhite); g2.fill(new RoundRectangle2D.Double(x, y, rectWidth, rectHeight, 10, 10));![]()
// fill Arc2D g2.setPaint(red); g2.fill(new Arc2D.Double(x, y, rectWidth, rectHeight, 90, 135, Arc2D.OPEN));![]()
// fill Ellipse2D.Double g2.setPaint(redtowhite); g2.fill (new Ellipse2D.Double(x, y, rectWidth, rectHeight));![]()
// fill and stroke GeneralPath int x3Points[] = {x, x+rectWidth, x, x+rectWidth}; int y3Points[] = {y, y+rectHeight, y+rectHeight, y}; GeneralPath filledPolygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD, x3Points.length); filledPolygon.moveTo(x3Points[0], y3Points[0]); for (int index = 1; index < x3Points.length; index++) { filledPolygon.lineTo(x3Points[index], y3Points[index]); }; filledPolygon.closePath(); g2.setPaint(red); g2.fill(filledPolygon);Note that this example uses the double-precision implementations of the geometries classes. Where applicable, float and double precision implementations of each of the geometries are provided as inner classes.
You can find the complete code for this example in
ShapesDemo2D.javaand an HTML file that includes the applet inShapesDemo2D.html.Defining Fancy Line Styles and Fill Patterns
You probably noticed that in the previous example, some of the shapes have thicker outline or are filled with a two-color gradient. Using the Java 2DStrokeandPaintclasses, you can easily define fancy line styles and fill patterns.Line Styles
Line styles are defined by the stroke attribute in the
Graphics2Drendering context. To set the stroke attribute, you create aBasicStrokeobject and pass it into theGraphics2DsetStrokemethod.A
BasicStrokeobject holds information about the line width, join style, endcap style, and dash style. This information is used when aShapeis rendered with thedrawmethod.The line width is the thickness of the line measured perpendicular to its trajectory. The line width is specified as a float value in user coordinate units, which are roughly equivalent to 1/72 of an inch.
The join style is the decoration that is applied where two line segments meet.
BasicStrokesupports three join styles:
![]()
![]()
![]()
JOIN_BEVEL JOIN_MITER JOIN_ROUND The endcap style is the decoration that is applied where a line segment ends.
BasicStrokesupports three endcap styles:The dash style defines the pattern of opaque and transparent sections applied along the length of the line. The dash style is defined by a dash array and a dash phase. The dash array defines the dash pattern--alternating elements in the array represent the dash length and the length of the space between dashes in user coordinate units. Element 0 represents the first dash, element 1 represents the first space, and so on. The dash phase is an offset into the dash pattern, also specified in user coordinate units. It indicates what part of the dash pattern is applied to the beginning of the line.
![]()
![]()
![]()
CAP_BUTT CAP_ROUND CAP_SQUARE Fill Patterns
Fill patterns are defined by the paint attribute in the
Graphics2Drendering context. To set the paint attribute, you create an instance of an object that implements thePaintinterface and pass it into theGraphics2DsetPaintmethod.Three classes implement the
Paintinterface:Color,GradientPaint, andTexturePaint.GradientPaintandTexturePaintare new in JDK 1.2.To create a
GradientPaint, you specify a beginning position and color, and an ending position and color. The gradient changes proportionally from one color to the other along the line connecting the two positions.The pattern for aTexturePaintis defined by aBufferedImage. To create aTexturePaint, you specify the image that contains the pattern and a rectangle that is used to replicate and anchor the pattern:Example: StrokeAndFill
The
StrokeAndFillprogram allows the user to select a graphics primitive, line style, and paint style and then either stroke the object's outline, fill it with the selected paint, or stroke the object in black and then fill it with the selected paint.How rendering is performed depends on which rendering option is selected:
- When the user selects stroke ,
Graphics2D.drawis called to perform the rendering. If text is selected as the primitive, the glyph outlines are retrieved and then rendered with thedrawmethod.- When the user selects fill ,
Graphics2D.fillorGraphics2D.drawStringis called to perform the rendering.- When the user selects stroke and fill ,
fillordrawStringis called to fill theShapeand thendrawis called to stroke its outline.
Note: To both fill and stroke a graphics primitive, you need to make two separate method calls:fillordrawStringto fill its interior anddrawto stroke its outline.
The three line styles used in this example--thin, thick, and dashed--are instances of
BasicStroke:The dash style in this example has 10 unit dashes alternating with 10 unit spaces. The beginning of the dash pattern is applied to the beginning of the line--the dash phase is set to 0.0.// Sets the Stroke. ... case 0 : g2.setStroke(new BasicStroke(3.0f)); break; case 1 : g2.setStroke(new BasicStroke(8.0f)); break; case 2 : float dash[] = {10.0f}; g2.setStroke(new BasicStroke(3.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash, 0.0f)); break;Three paint styles are used in this example--solid, gradient, and polka. The solid color paint style is an instance of
Color, the gradient is an instance ofGradientPaint, and the pattern is an instance ofTexturePaint:Here's the code for the// Sets the Paint. ... case 0 : g2.setPaint(Color.blue); break; case 1 : g2.setPaint(new GradientPaint(0, 0, Color.lightGray, w-250, h, Color.blue, false)); break; case 2 : BufferedImage bi = new BufferedImage(5, 5, BufferedImage.TYPE_INT_RGB); Graphics2D big = bi.createGraphics(); big.setColor(Color.blue); big.fillRect(0, 0, 5, 5); big.setColor(Color.lightGray); big.fillOval(0, 0, 5, 5); Rectangle r = new Rectangle(0,0,5,5); g2.setPaint(new TexturePaint(bi, r)); break;StrokeAndFill.javaprogram and an HTML file that includes the appletStrokeAndFill.html.
![]()
Displaying Graphics with Graphics2D