Whole document tree
2.4 Rendering Graphics PrimitivesGraphics2D provides rendering methods for Shapes, Text, and Images: To stroke and fill a shape, you must call both the draw and fill methods. 2.4.1 Drawing a ShapeThe outline of any Shape can be rendered with the Graphics2D.draw method. The draw methods from previous versions of the JDK software are also supported: drawLine, drawRect, drawRoundRect, drawOv al, drawArc, drawPolyline, drawPolygon, draw3DRect. In the following example, a GeneralPath object is used to define a star and a BasicStroke object is added to the Graphics2D context to define the star's line with and join attributes. public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; // create and set the stroke g2.setStroke(new BasicStroke(4.0f)); // Create a star using a general path object GeneralPath p = new GeneralPath(GeneralPath.NON_ZERO); p.moveTo(- 100.0f, - 25.0f); p.lineTo(+ 100.0f, - 25.0f); p.lineTo(- 50.0f, + 100.0f); p.lineTo(+ 0.0f, - 100.0f); p.lineTo(+ 50.0f, + 100.0f); p.closePath(); // translate origin towards center of canvas g2.translate(100.0f, 100.0f); // render the star's path g2.draw(p); } 2.4.2 Filling a ShapeThe Graphics2D.fill method can be used to fill any Shape. When a Shape is filled, the area within its path is rendered with the Graphics2D context's current Paint attribute--a In the following example, setColor is called to define a green fill for a Rectangle2D. public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setPaint(Color.green); Rectangle2D r2 = new Rectangle2D.Float(25,25,150,150); g2.fill(r2); } 2.4.3 Rendering TextTo render a text string, you call Graphics2D.drawString, passing in the string that you want to render. For more information about rendering text and selecting fonts, see "Fonts and Text Layout" . 2.4.4 Rendering ImagesTo render an Image, you create the Image and call Graphics2D.drawImage. For more information about processing and rendering images, see "Imaging". CONTENTS | PREV | NEXT Copyright © 1997-1999 Sun Microsystems, Inc. All Rights Reserved. |