Docsity

The Graphics in the Java ll - Paper | CS 4470, Papers of Software Development

Partial preview of the text

Download The Graphics in the Java ll - Paper | CS 4470 and more Papers Software Development in PDF only on Docsity!

Chapter

Java 2D:

Graphics in

Java 2

Topics in This Chapter

  • Drawing 2D shapes
  • Tiling an image inside a shape
  • Using local fonts
  • Drawing with custom pen settings
  • Changing the opaqueness of objects
  • Translating and rotating coordinate systems

Chapter

nyone who has even lightly ventured into developing detailed graphical pro- grams with the Abstract Windowing Toolkit (AWT) has quickly realized that the capabilities of the Graphics object are rather limited—not surprisingly, since Sun developed the AWT over a short period when moving Java from embedded applications to the World Wide Web. Shortcomings of the AWT include limited avail- able fonts, lines drawn with a single-pixel width, shapes painted only in solid colors, and the inability to properly scale drawings prior to printing. Java 2D is probably the second most significant addition to the Java 2 Platform, surpassed only by the Swing GUI components. The Java 2D API provides a robust package of drawing and imaging tools to develop elegant, professional, high-quality graphics. The following important Java 2D capabilities are covered in this chapter:

  • Colors and patterns: graphics can be painted with color gradients and fill patterns.
  • Transparent drawing: opaqueness of a shape is controlled through an alpha transparency value.
  • Local fonts: all local fonts on the platform are available for drawing text.
  • Explicit control of the drawing pen: thickness of lines, dashing patterns, and segment connection styles are available.
  • Transformations of the coordinate system—translations, scaling, rotations, and shearing—are available.

A

10.1 Getting Started with Java 2D 361

The general approach for drawing in Java 2D is outlined as follows.

Listing 10.1 Drawing graphics in Java 1.

public void paint(Graphics g) { // Set pen parameters g.setColor(someColor); g.setFont(someLimitedFont);

// Draw a shape g.drawString(...); g.drawLine(...) g.drawRect(...); // outline g.fillRect(...); // solid g.drawPolygon(...); // outline g.fillPolygon(...); // solid g.drawOval(...); // outline g.fillOval(...); // solid ... }

Listing 10.2 Drawing graphics in the Java 2 Platform

public void paintComponent(Graphics g) { // Clear background if opaque super.paintComponent(g); // Cast Graphics to Graphics2D Graphics2D g2d = (Graphics2D)g; // Set pen parameters g2d.setPaint(fillColorOrPattern); g2d.setStroke(penThicknessOrPattern); g2d.setComposite(someAlphaComposite); g2d.setFont(anyFont); g2d.translate(...); g2d.rotate(...); g2d.scale(...); g2d.shear(...); g2d.setTransform(someAffineTransform); // Allocate a shape SomeShape s = new SomeShape (...); // Draw shape g2d.draw(s); // outline g2d.fill(s); // solid }

362 Chapter 10 Java 2D: Graphics in Java 2

Cast the Graphics object to a Graphics2D object. Always call the paintComponent method of the superclass first, because the default implementation of Swing components is to call the paint method of the associated ComponentUI; this approach maintains the component look and feel. In addition, the default paintComponent method clears the off-screen pixmap because Swing components implement double buffering. Next, cast the Graphics object to a Graphics2D object for Java 2D drawing.

public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D)g; g2d.doSomeStuff(...); ... }

Core Approach

When overriding the paintComponent method of a Swing component, always call super.paintComponent.

Modify drawing parameters (optional). Drawing parameters are applied to the Graphics2D object, not to the Shape object. Changes to the graphics context (Graphics2D) apply to every subse- quent drawing of a Shape.

g2d. setPaint (fillColorOrPattern); g2d. setStroke (penThicknessOrPattern); g2d. setComposite (someAlphaComposite); g2d. setFont (someFont); g2d. translate (...); g2d. rotate (...); g2d. scale (...); g2d. shear (...); g2d. setTransform (someAffineTransform);

Create a Shape object.

Rectangle2D.Double rect = ...; Ellipse2D.Double ellipse = ...; Polygon poly = ...; GeneralPath path = ...; // Satisfies Shape interface SomeShapeYouDefined shape = ...;

364 Chapter 10 Java 2D: Graphics in Java 2

Java 2D supports fractional coordinates to permit proper scaling and transfor- mations of the coordinate system. Java 2D objects live in the User Coordinate Space where the axes are defined by floating-point units. When the graphics are rendered on the screen or a printer, the User Coordinate Space is trans- formed to the Device Coordinate Space. The transformation maps 72 User Coordinate Space units to one physical inch on the output device. Thus, before the graphics are rendered on the physical device, fractional values are con- verted to their nearest integral values.

public void fill(Shape shape) This method draws a solid version of the shape, based on the current settings of the Graphics2D context. See the draw method for details of positioning.

public void rotate(double theta) This method applies a rotation of theta radians to the Graphics2D transfor- mation. The point of rotation is about (x, y)=(0, 0). This rotation is added to any existing rotations of the Graphics2D context. See Section 10.7 (Coordi- nate Transformations).

public void rotate(double theta, double x, double y) This method also applies a rotation of theta radians to the Graphics2D trans- formation. However, the point of rotation is about (x, y). See Section 10. (Coordinate Transformations) for details.

public void scale(double xscale, yscale) This method applies a linear scaling to the x- and y-axis. Values greater than 1. expand the axis, and values less than 1.0 shrink the axis. A value of - 1 for xscale results in a mirror image reflected across the x-axis. A yscale value of - 1 results in a reflection about the y-axis.

public void setComposite(Composite rule) This method specifies how the pixels of a new shape are combined with the existing background pixels. You can specify a custom composition rule or apply one of the predefined AlphaComposite rules: AlphaCompos- ite.Clear, AlphaComposite.DstIn, AlphaComposite.DstOut, AlphaComposite.DstOver, AlphaComposite.Src, AlphaCompos- ite.SrcIn, AlphaComposite.SrcOut, AlphaComposite.ScrOver.

To create a custom AlphaComposite rule, call getInstance as in g2d.setComposite(AlphaComposite.SrcOver);

10.1 Getting Started with Java 2D 365

or

int type = AlphaComposite.SRC_OVER; float alpha = 0.75f; AlphaComposite rule = AlphaComposite.getInstance(type, alpha); g2d.setComposite(rule);

The second approach permits you to set the alpha value associated with com- posite rule, which controls the transparency of the shape. By default, the trans- parency value is 1.0f (opaque). See Section 10.4 (Transparent Drawing) for details. Clarification of the mixing rules is given by T. Porter and T. Duff in “Compositing Digital Images,” SIGGRAPH 84 , pp. 253–259.

public void setPaint(Paint paint) This method sets the painting style of the Graphics2D context. Any style that implements the Paint interface is legal. Existing styles in the Java 2 Platform include a solid Color, a GradientPaint, and a TexturePaint.

public void setRenderingHints(Map hints)

This method allows you to control the quality of the 2D drawing. The AWT includes a RenderingHints class that implements the Map interface and pro- vides a rich suite of predefined constants. Quality aspects that can be con- trolled include antialiasing of shape and text edges, dithering and color rendering on certain displays, interpolation between points in transformations, and fractional text positioning. Typically, antialiasing is turned on, and the image rendering is set to quality, not speed:

RenderingHints hints = new RenderingHints( RenderingHints.KEY_ANTIALIASING, RengeringHints.VALUE_ANTIALIAS_ON); hints.add(new RenderingHints( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));

public void setStroke(Stroke pen)

The Graphics2D context determines how to draw the outline of a shape, based on the current Stroke. This method sets the drawing Stroke to the behavior defined by pen. A user-defined pen must implement the Stroke interface. The AWT includes a BasicStroke class to define the end styles of a line segment, to specify the joining styles of line segments, and to create dashing patterns. See Section 10.6 (Stroke Styles) for details.

public void transform(AffineTransform matrix) This method applies the Affine transformation, matrix, to the existing transfor- mation of the Graphics2D context. The Affine transformation can include both a translation and a rotation. See Section 10.7 (Coordinate Transformations).

10.2 Drawing Shapes 367

Most of the Shape classes define both a Shape.Double and a Shape.Float ver- sion of the class. Depending on the version of the class, the coordinate locations are stored as either double precision numbers (Shape.Double) or single precision numbers (Shape.Float). The idea is that single precision coordinates might be slightly faster to manipulate on some platforms. You can still call the familiar drawXxx methods of the Graphics class if you like; the Graphics2D object inher- its from the Graphics object. This approach is necessary for drawString and

drawImage and possibly is convenient for draw3DRect.

Shape Classes

Arguments to the Graphics2D draw and fill methods must implement the Shape interface. You can create your own shapes, of course, but you can also use major built-in classes: Arc2D, Area, CubicCurve2D, Ellipse2D, GeneralPath, Line2D, QuadCurve2D, Rectangle2D, and RoundRectangle2D. Each of these classes is contained in the java.awt.geom package. Each of these classes, except for Area, Polygon, and Rectangle, has float and double constructors.

The classes Polygon and Rectangle, holdovers from Java 1.1, also implement the Shape interface. These two shapes are covered in Section 9.11 (Graphics Operations).

The most common constructors for these Shapes follow.

public Arc2D.Float(float left, float top, float width, float height, float startAngle, float deltaAngle, int closure) public Arc2D.Double(double left, double top, double width, double height, double startAngle, double deltaAngle, int closure) These constructors create an arc by selecting a portion of a full ellipse whose bounding rectangle has an upper-left corner located at the (left, top). The vertex of the arc (ellipse) is located at the origin of the bounding rectangle. The reference for the start angle is the positive x-axis. Angles are specified in degrees and represent arc degrees, not true degrees. Arc angles are defined such that the 45 degree line runs from the ellipse center to the upper-right cor- ner of the bounding rectangle. The arc closure is one of Arc2D.CHORD, Arc2D.OPEN, or Arc2D.PIE.

public Area(Shape shape) This constructor creates an Area with the given Shape. Areas support geo- metrical operations, for example: add, subtract, intersect, and exclusiveOr.

368 Chapter 10 Java 2D: Graphics in Java 2

public CubicCurve2D.Float(float xStart, float yStart, float pX, float pY, float qX, float qY, float xEnd, float yEnd) public CubicCurve2D.Double(double xStart, double yStart, double pX, double pY, double qX, double qY, double xEnd, double yEnd) These constructors create a CubicCurve2D shape representing a curve (spline) from (xStart, yStart) to (xEnd, yEnd). The curve has two control points (pX, pY) and (qX, qY) that impact the curvature of the line segment join- ing the two end points.

public Ellipse2D.Float(float left, float top, float width, float height) public Ellipse2D.Double(double left, double top, double width, double height) These constructors create an ellipse bounded by a rectangle of dimension width by height. The Ellipse2D class inherits from the Rectangular- Shape class and contains the same methods as common to Rectangle2D and RoundRectangle2D.

public GeneralPath() A GeneralPath is an interesting class because you can define all the line seg- ments to create a brand-new Shape. This class supports a handful of methods to add lines and Bézier (cubic) curves to the path: closePath, curveTo, lineTo, moveTo, and quadTo. Appending a path segment to a General- Path without first performing an initial moveTo generates an IllegalPath- StateException. An example of creating a GeneralPath follows: GeneralPath path = new GeneralPath(); path.moveTo(100,100); path.lineTo(300,205); path.quadTo(205,250,340,300); path.lineTo(340,350); path.closePath();

public Line2D.Float(float xStart, float yStart, float xEnd, float yEnd) public Line2D.Double(double xStart, double yStart, double xEnd, double yEnd) These constructors create a Line2D shape representing a line segment from (xStart, yStart) to (xEnd, yEnd).

370 Chapter 10 Java 2D: Graphics in Java 2

Most of the code examples throughout this chapter are presented as Java applica- tions. To convert the examples to applets, follow the given template:

import java.awt.; import javax.swing.; public class Your Applet extends JApplet { public void init() { JPanel panel = new ChapterExample (); panel.setBackground(Color.white); getContentPane(). add(panel) ; } }

The basic idea is to create a JApplet and add the chapter example, which is implemented as a JPanel, to the contentPane of the JApplet. Depending on the particular example you are converting, you may need to set the background color of the JPanel. Once the corresponding HTML file is created (with an applet of the same dimensions as the original JFrame), you can either use appletviewer or convert the HTML file to support the Java Plug-In. See Section 9.9 (The Java Plug-In) for details on converting the HTML file.

Listing 10.3 ShapeExample.java

import javax.swing.; // For JPanel, etc. import java.awt.; // For Graphics, etc. import java.awt.geom.*; // For Ellipse2D, etc.

/** An example of drawing/filling shapes with Java 2D in

  • Java 1.2 and later. */

public class ShapeExample extends JPanel { private Ellipse2D.Double circle = new Ellipse2D.Double(10, 10, 350, 350); private Rectangle2D.Double square = new Rectangle2D.Double(10, 10, 350, 350);

public void paintComponent(Graphics g) { clear(g); Graphics2D g2d = (Graphics2D)g; g2d.fill(circle); g2d.draw(square); }

(continued)

10.3 Paint Styles 371

10.3 Paint Styles

When you fill a Shape, the Graphics2D object uses the settings associated with the internal Paint attribute. The Paint setting can be a Color (solid color), a Gradi- entPaint (gradient fill gradually combining two colors), a TexturePaint (tiled image), or a new version of Paint that you write yourself. Use setPaint and get-

// super.paintComponent clears off screen pixmap, // since we're using double buffering by default. protected void clear(Graphics g) { super.paintComponent(g); }

protected Ellipse2D.Double getCircle() { return(circle); }

public static void main(String[] args) { WindowUtilities.openInJFrame(new ShapeExample(), 380, 400); } }

Listing 10.3 ShapeExample.java (continued)

Figure 10–1 An ellipse (circle) drawn with a box outline in Java 2D.

10.3 Paint Styles 373

will smoothly transition along the gradient line, with parallel color bands extending orthogonally to the gradient line. Depending on the value of a boolean flag, the color pattern will repeat along the extended gradient line until the end of the shape is reached.

public GradientPaint(float xStart, float yStart, Color colorStart, float xEnd, float yEnd, Color colorEnd)

This constructor creates a GradientPaint, beginning with a color of color- Start at (xStart, yStart) and finishing with a color of colorEnd at (xEnd, yEnd). The gradient is nonrepeating (a single gradient cycle).

public GradientPaint(float xStart, float yStart, Color colorStart, float xEnd, float yEnd, Color colorEend, boolean repeat)

This constructor is the same as the preceding constructor, except that a boolean flag, repeat, can be set to produce a pattern that continues to repeat beyond the end point (cyclic).

TexturePaint

A TexturePaint is simply an image that is tiled across the shape. When creating a textured paint, you need to specify both the image on the tile and the tile size.

public TexturePaint(BufferedImage image, Rectangle2D tilesize)

The TexturePaint constructor maps a BufferedImage to a Rectangle2D and then tiles the rectangle. Creating a BufferedImage from a GIF or JPEG file is a pain. First, load an Image normally, get the size of the image, create a BufferedImage that sizes with Buffered- Image.TYPE_INT_ARGB as the image type, get the BufferedImage's Graphics object through createGraphics, then draw the Image into the BufferedImage using drawImage.

Listing 10.4 is an example of applying a gradient fill prior to drawing a circle. The gradient begins with a red color (Color.red) located at (0, 0) and gradually changes to a yellow color (Color.yellow) located at (185, 185) near the center of the circle. The gradient fill pattern repeats across the remaining area of the circle, as shown in Figure 10–2.

374 Chapter 10 Java 2D: Graphics in Java 2

Listing 10.4 GradientPaintExample.java

import java.awt.*;

/** An example of applying a gradient fill to a circle. The

  • color definition starts with red at (0,0), gradually
  • changing to yellow at (175,175). */

public class GradientPaintExample extends ShapeExample { private GradientPaint gradient = new GradientPaint(0, 0, Color.red, 175, 175, Color.yellow, true); // true means to repeat pattern

public void paintComponent(Graphics g) { clear(g); Graphics2D g2d = (Graphics2D)g; drawGradientCircle(g2d); }

protected void drawGradientCircle(Graphics2D g2d) { g2d.setPaint(gradient); g2d.fill(getCircle()); g2d.setPaint(Color.black); g2d.draw(getCircle()); }

public static void main(String[] args) { WindowUtilities.openInJFrame(new GradientPaintExample(), 380, 400); } }

Figure 10– 2 A circle drawn with a

gradient fill in Java 2D.

376 Chapter 10 Java 2D: Graphics in Java 2

Listing 10.5 TiledImages.java

import javax.swing.; import java.awt.; import java.awt.geom.; import java.awt.image.;

/** An example of using TexturePaint to fill objects with tiled

  • images. Uses the getBufferedImage method of ImageUtilities
  • to load an Image from a file and turn that into a
  • BufferedImage. */

public class TiledImages extends JPanel { private String dir = System.getProperty("user.dir"); private String imageFile1 = dir + "/images/marty.jpg"; private TexturePaint imagePaint1; private Rectangle imageRect; private String imageFile2 = dir + "/images/bluedrop.gif"; private TexturePaint imagePaint2; private int[] xPoints = { 30, 700, 400 }; private int[] yPoints = { 30, 30, 600 }; private Polygon imageTriangle = new Polygon(xPoints, yPoints, 3); public TiledImages() { BufferedImage image = ImageUtilities.getBufferedImage(imageFile1, this); imageRect = new Rectangle(235, 70, image.getWidth(), image.getHeight()); imagePaint1 = new TexturePaint(image, imageRect); image = ImageUtilities.getBufferedImage(imageFile2, this); imagePaint2 = new TexturePaint(image, new Rectangle(0, 0, 32, 32)); }

public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D)g; g2d.setPaint(imagePaint2); g2d.fill(imageTriangle); g2d.setPaint(Color.blue); g2d.setStroke(new BasicStroke(5)); g2d.draw(imageTriangle); g2d.setPaint(imagePaint1); g2d.fill(imageRect); g2d.setPaint(Color.black); g2d.draw(imageRect); }

public static void main(String[] args) { WindowUtilities.openInJFrame(new TiledImages(), 750, 650); } }

10.3 Paint Styles 377

Listing 10.6 ImageUtilities.java

import java.awt.; import java.awt.image.;

/** A class that simplifies a few common image operations, in

  • particular, creating a BufferedImage from an image file and
  • using MediaTracker to wait until an image or several images
  • are done loading. */

public class ImageUtilities {

/** Create Image from a file, then turn that into a

  • BufferedImage. */

public static BufferedImage getBufferedImage(String imageFile, Component c) { Image image = c.getToolkit().getImage(imageFile); waitForImage(image, c);

BufferedImage bufferedImage = new BufferedImage(image.getWidth(c), image.getHeight(c), BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bufferedImage.createGraphics(); g2d.drawImage(image, 0, 0, c); return(bufferedImage); }

/** Take an Image associated with a file, and wait until it is

  • done loading (just a simple application of MediaTracker).
  • If you are loading multiple images, don't use this
  • consecutive times; instead, use the version that takes
  • an array of images. */

public static boolean waitForImage(Image image, Component c) { MediaTracker tracker = new MediaTracker(c); tracker.addImage(image, 0); try { tracker.waitForAll(); } catch(InterruptedException ie) {} return(!tracker.isErrorAny()); }

(continued)