All Packages  Class Hierarchy  This Package  Previous  Next  Index  

Class java.awt.Graphics2D

java.lang.Object
    |
    +----java.awt.Graphics
            |
            +----java.awt.Graphics2D

public abstract class Graphics2D
extends Graphics
This is the fundamental class for 2D rendering in Java. This class extends the original java.awt.Graphics class to provide more sophisticated control over geometry, coordinate transformation, color management, and text layout.

Coordinate Spaces

All coordinates that are given to a Graphics2D object are treated as being in a virtual coordinate system which is called the User Coordinate Space, or User Space. The Graphics2D object contains a Transform object as part of its rendering state that defines how to convert coordinates from this user space to coordinates in the Device Coordinate Space, or Device Space.

Coordinates in device space usually refer to individual device pixels and are aligned in the infinitely thin gaps between these pixels. Some Graphics2D objects may be used to capture rendering operations for storage into a graphics metafile for playback on a concrete device of unknown physical resolution at a later time. Since the resolution may not be known when the rendering operations are captured, the Transform will be set up to transform user coordinates to a virtual device space that typically approximates the expected resolution of the target device, though further transformation may need to be applied at playback time if the estimate is incorrect.

Some of the operations performed by the rendering attribute objects may operate in the device space, but all methods that are defined on the Graphics2D object work with user space coordinates.

The default transform when a Graphics2D object is created will be specified by the GraphicsConfiguration for the target of the Graphics2D (a Component or Image). This default transform will map the user space coordinate system to screen and printer device coordinates such that the origin maps to the upper left hand corner of the target region of the device with increasing X coordinates extending to the right and increasing Y coordinates extending downward. The scaling of the default transform for screen devices will be set to identity for screen devices. The scaling of the default transform for printers and other high resolution devices will be set to approximate 72 user space coordinates per device inch. For image buffers, the default transform will be the Identity transform.

Rendering Outline

Rendering in the Java 2D API can be described by a 4-step conceptual process controlled by the various rendering attributes in the Graphics2D object. The renderer may optimize many of these steps, either by caching the results for future calls, by collapsing multiple virtual steps into a single operation, or by recognizing various attributes as common simple cases that can be eliminated by modifying other parts of the operation.

As a behavioral reference, the steps can be described in the following way:

  1. Determine where to render. This step can be further broken down according to the type of rendering operation as follows:
    Shape operations
    1. If the operation is a draw(Shape) operation, then the shape is converted into a shape to fill using the createStrokedShape() method on the current Stroke.
    2. The shape is transformed from user space to device space using the current Transform.
    3. The outline of the Shape is extracted using a PathIterator using the Shape.getPathIterator() method.
    4. If the Graphics2D object is not able to handle the curved segments that a PathIterator object can return, then it may call the alternat getPathIterator() method which flattens the shape.
    Text operations
    1. The set of glyphs required to render the indicated string are determined as follows:
      • If the argument is a String, then the current Font is asked to convert the Unicode characters in the String into a GlyphSet with whatever basic layout algorithm the font implements.
      • If the argument is a StyledString, the StyledString is asked to convert itself to a GlyphSet according to its embedded font attributes. The StyledString may implement more sophisticated glyph layout algorithms that perform Unicode bi-directional layout adjustments automatically for multiple fonts of differing writing directions.
      • If the argument is a GlyphSet, then the GlyphSet object already contains the appropriate font-specific glyph codes with explicit coordinates for the position of each glyph.
    2. The current Font is queried to obtain outlines for the indicated glyphs. These outlines are treated as shapes in user space relative to the position of each glyph that was determined in step 1.
    3. The outline of the characters are filled as indicated above under Shape operations
    Image operations
    1. The bounding box of the source image defines the region of interest in a coordinate system local to the Image object, called Image Space.
    2. If an optional transform is supplied to the drawImage() method call, then this transform is used to transform the bounding box from image space to user space, otherwise the bounding box is treated as if it already was in user space.
    3. The bounding box of the source image is then transformed from user space into device space using the current transform of the Graphics2D. Note that the result of transforming the bounding box will not necessarily result in a rectangular region in device space and for some custom transforms may not even result in a quadrilateral region.
  2. Constrain the rendering operation to the current Clip. The clip was originally specified by a shape in user space and was converted into device space by the Transform in effect at the time it was modified.
  3. Determine what colors to render as the renderer scan converts the associated shape in device space.
  4. Apply the colors to the destination drawing surface using the current Composite object.

Default values

The default values for the various rendering attributes are:
Color
The color of the Component.
Font
The font of the Component.
Stroke
A square pen with a linewidth of 1, no dashing, miter segment joins and non-projecting end caps.
Transform
The default for the GraphicsConfiguration of the Component.
Composite
The Porter-Duff Source Over Destination rule.
Clip
No rendering clip, output is clipped to the Component

Rendering compatibility issue

The rendering model presented by the pre-Java 2D API Graphics class was based on a pixelization model that specified that coordinates were infinitely thin, lying between the pixels, and that drawing operations were performed by dragging a one-pixel square Pen along the path hanging down and to the right of the anchor point on the path.

The behavior of these operations given the model presented here is unclear if the current Stroke specifies a wide pen, or if there is a non-identity Transform being applied.

That rendering model was consistent with the capabilities of most of the existing class of platform renderers that needed to resolve integer coordinates to a discrete pen that must fall completely on a given number of pixels. Since the Java 2D API is capable of driving an antialiasing renderer it no longer makes sense to choose a bias direction for a wide pen since sub-pixel positioning of the pen can be made visible to the user via the blending that occurs along the edges of the traversal of the pen. It is thus, no longer true that a 1-pixel wide pen must choose to fall on pixel N as opposed to pixel N+1; it can now fall partially on both pixels.

When antialiasing is turned off with the ANTIALIAS_OFF hint, the underlying renderer may still need to apply a bias in order to resolve the conflict of which pixel to modify when the pen is exactly straddling a pixel boundary (such as when it is drawn along an integer coordinate in device space). But when antialiasing is enabled, no biasing of the pen needs to occur and so no bias should be explicitly specified by the rendering model.

Thus, there remains the problem of how to define the operation of the legacy rendering operations inherited from the Graphics class to be compatible with existing rendering behavior and to be predictable and unsurprising under all possible settings of the latest rendering attributes.

To provide predictability we will define operations for all of the legacy methods that map onto the more general draw(Shape) and fill(Shape) methods. Such a specification will thus be clear how it extends based on various settings of Stroke and Transform attributes, and rendering hints.

To provide compatibility with previous rendering behavior it is important to specify a definition that performs identically under the default attribute settings. In particular, the default Stroke is a BasicStroke with a width of 1 and no dashing, and the default Transform for screen drawing is an Identity transform. Unfortunately, the default antialiasing rendering hint is ANTIALIAS_DEFAULT which may be enabled on some implementations and not on others. This means that the definition of these operations needs to be invariant under antialiasing.

We now define the following generalizations of the various legacy methods which can be shown to be identical to the previously specified behavior under the default attributes:

The existing Graphics class defined only the single setColor method to control the color to be painted. Since the Java 2D API extends the Color object to implement the new Paint interface, the existing setColor method is now a convenience method for setting the current Paint to a Color object. setColor(c) is thus equivalent to setPaint(c).

The existing Graphics class defined two methods for controlling how colors were applied to the destination. The setPaintMode() method will now be implemented as a convenience method to set the default Composite, equivalent to setComposite(new AlphaComposite(SRC_OVER)). The setXORMode(Color xorcolor) method will now be implemented as a convenience method to set a special Composite object which ignores the Alpha components of source colors and sets the destination color to the value:

 dstpixel = (PixelOf(srccolor) ^ PixelOf(xorcolor) ^ dstpixel);
 


Variable Index

 o ANTIALIAS_DEFAULT
Rendering is done with the platform default antialiasing mode.
 o ANTIALIAS_OFF
Rendering is done without antialiasing.
 o ANTIALIAS_ON
Rendering is done with antialiasing.
 o ANTIALIASING
Antialiasing hint category.
 o RENDER_DEFAULT
The platform default algorithms are chosen for rendering.
 o RENDER_QUALITY
Appropriate rendering algorithms are chosen with a preference for output quality.
 o RENDER_SPEED
Appropriate rendering algorithms are chosen with a preference for output speed.
 o RENDERING
Rendering hint category.

Constructor Index

 o Graphics2D()
Constructs a new Graphics2D object.

Method Index

 o clip(Shape)
Intersects the current clip with the interior of the specified Shape and sets the current clip to the resulting intersection.
 o draw(Shape)
Strokes the outline of a Shape using the settings of the current graphics state.
 o drawImage(BufferedImage, BufferedImageOp, int, int)
Draws a BufferedImage that is filtered with a BufferedImageOp.
 o drawImage(Image, AffineTransform, ImageObserver)
Draws an image, applying a transform from image space into user space before drawing.
 o drawRenderedImage(RenderedImage, AffineTransform, ImageObserver)
Draws an image, applying a transform from image space into user space before drawing.
 o drawString(GlyphSet, float, float)
Draws a GlyphSet.
 o drawString(String, float, float)
Draws a string of text.
 o drawString(StyledString, float, float)
Draws a StyledString.
 o drawString(TextLayout, float, float)
 o fill(Shape)
Fills the interior of a Shape using the settings of the current graphics state.
 o getBackground()
Returns the background color used for clearing a region.
 o getComposite()
Returns the current Composite in the Graphics2D state.
 o getDeviceConfiguration()
Returns the device configuration associated with this Graphics2D.
 o getPaint()
Returns the current Paint in the Graphics2D state.
 o getRenderingHints(int)
Returns the preferences for the rendering algorithms.
 o getStroke()
Returns the current Stroke in the Graphics2D state.
 o getTransform()
Returns the current Transform in the Graphics2D state.
 o hit(Rectangle, Shape, boolean)
Checks to see if the outline of a Shape intersects the specified Rectangle in device space.
 o hitString(Rectangle, StyledString, float, float)
Checks to see if the StyledString intersects the specified Rectangle in device space.
 o setBackground(Color)
Sets the background color in this context used for clearing a region.
 o setComposite(Composite)
Sets the Composite in the current graphics state.
 o setPaint(Paint)
Sets the Paint in the current graphics state.
 o setRenderingHints(int, int)
Sets the preferences for the rendering algorithms.
 o setStroke(Stroke)
Sets the Stroke in the current graphics state.
 o setTransform(AffineTransform)
Sets the Transform in the current graphics state.
 o transform(AffineTransform)
Composes a Transform object with the transform in this Graphics2D according to the rule last-specified-first-applied.

Variables

 o ANTIALIASING
public static final int ANTIALIASING
Antialiasing hint category.

 o ANTIALIAS_ON
public static final int ANTIALIAS_ON
Rendering is done with antialiasing.

 o ANTIALIAS_OFF
public static final int ANTIALIAS_OFF
Rendering is done without antialiasing.

 o ANTIALIAS_DEFAULT
public static final int ANTIALIAS_DEFAULT
Rendering is done with the platform default antialiasing mode.

 o RENDERING
public static final int RENDERING
Rendering hint category.

 o RENDER_SPEED
public static final int RENDER_SPEED
Appropriate rendering algorithms are chosen with a preference for output speed.

 o RENDER_QUALITY
public static final int RENDER_QUALITY
Appropriate rendering algorithms are chosen with a preference for output quality.

 o RENDER_DEFAULT
public static final int RENDER_DEFAULT
The platform default algorithms are chosen for rendering.

Constructors

 o Graphics2D
protected Graphics2D()
Constructs a new Graphics2D object. Since Graphics2D is an abstract class, and since it must be customized by subclasses for different output devices, Graphics2D objects cannot be created directly. Instead, Graphics2D objects must be obtained from another Graphics2D object or created by a Component.

See Also:
getGraphics, create

Methods

 o draw
public abstract void draw(Shape s)
Strokes the outline of a Shape using the settings of the current graphics state. The rendering attributes applied include the clip, transform, paint or color, composite and stroke attributes.

Parameters:
s - The shape to be drawn.
See Also:
setStroke, setPaint, setColor, transform, setTransform, clip, setClip, setComposite
 o drawImage
public abstract void drawImage(Image img,
                               AffineTransform xform,
                               ImageObserver obs)
Draws an image, applying a transform from image space into user space before drawing. The transformation from user space into device space is done with the current transform in the Graphics2D. The given transformation is applied to the image before the transform attribute in the Graphics2D state is applied. The rendering attributes applied include the clip, transform, and composite attributes. Note that the result is undefined, if the given transform is noninvertible.

Parameters:
img - The image to be drawn.
xform - The transformation from image space into user space.
obs - The image observer to be notified as more of the image is converted.
See Also:
transform, setTransform, setComposite, clip, setClip
 o drawImage
public abstract void drawImage(BufferedImage img,
                               BufferedImageOp op,
                               int x,
                               int y)
Draws a BufferedImage that is filtered with a BufferedImageOp. The rendering attributes applied include the clip, transform and composite attributes. This is equivalent to:
 img1 = op.filter(img, null);
 drawImage(img1, new AffineTransform(1f,0f,0f,1f,x,y), null);
 

Parameters:
op - The filter to be applied to the image before drawing.
img - The BufferedImage to be drawn.
x,y - The location in user space where the image should be drawn.
See Also:
transform, setTransform, setComposite, clip, setClip
 o drawRenderedImage
public abstract void drawRenderedImage(RenderedImage img,
                                       AffineTransform xform,
                                       ImageObserver obs)
Draws an image, applying a transform from image space into user space before drawing. The transformation from user space into device space is done with the current transform in the Graphics2D. The given transformation is applied to the image before the transform attribute in the Graphics2D state is applied. The rendering attributes applied include the clip, transform, and composite attributes. Note that the result is undefined, if the given transform is noninvertible.

Parameters:
img - The image to be drawn.
xform - The transformation from image space into user space.
obs - The image observer to be notified as more of the image is converted.
See Also:
transform, setTransform, setComposite, clip, setClip
 o drawString
public abstract void drawString(String s,
                                float x,
                                float y)
Draws a string of text. The rendering attributes applied include the clip, transform, paint or color, font and composite attributes.

Parameters:
s - The string to be drawn.
x,y - The coordinates where the string should be drawn.
See Also:
setPaint, setColor, setFont, transform, setTransform, setComposite, clip, setClip
 o drawString
public abstract void drawString(StyledString s,
                                float x,
                                float y)
Draws a StyledString. The rendering attributes applied include the clip, transform, paint or color, and composite attributes. A Font is associated with each character in the StyledString.

Parameters:
s - The StyledString to be drawn.
x,y - The coordinates where the StyledString should be drawn.
See Also:
setPaint, setColor, transform, setTransform, setComposite, clip, setClip, Font
 o drawString
public abstract void drawString(GlyphSet g,
                                float x,
                                float y)
Draws a GlyphSet. The rendering attributes applied include the clip, transform, paint or color, and composite attributes. The glyphSet specifies individual glyphs from a Font.

Parameters:
g - The GlyphSet to be drawn.
x,y - The coordinates where the glyphs should be drawn.
See Also:
setPaint, setColor, transform, setTransform, setComposite, clip, setClip
 o drawString
public abstract void drawString(TextLayout text,
                                float x,
                                float y)
 o fill
public abstract void fill(Shape s)
Fills the interior of a Shape using the settings of the current graphics state. The rendering attributes applied include the clip, transform, paint or color, and composite.

See Also:
setPaint, setColor, transform, setTransform, setComposite, clip, setClip
 o hit
public abstract boolean hit(Rectangle rect,
                            Shape s,
                            boolean onStroke)
Checks to see if the outline of a Shape intersects the specified Rectangle in device space. The rendering attributes taken into account include the clip, transform, and stroke attributes.

Parameters:
rect - The area in device space to check for a hit.
s - The shape to check for a hit.
onStroke - Flag to choose between testing the stroked or the filled shape.
Returns:
True if there is a hit, false otherwise.
See Also:
setStroke, fill, draw, transform, setTransform, clip, setClip
 o hitString
public abstract boolean hitString(Rectangle rect,
                                  StyledString s,
                                  float x,
                                  float y)
Checks to see if the StyledString intersects the specified Rectangle in device space. The rendering attributes taken into account include the clip and transform.

Parameters:
rect - The area in device space to check for a hit.
s - The StyledString to check for a hit.
x,y - The coordinates where the StyledString should be hit tested.
Returns:
True if there is a hit, false otherwise.
See Also:
drawString, transform, setTransform, clip, setClip
 o getDeviceConfiguration
public abstract GraphicsConfiguration getDeviceConfiguration()
Returns the device configuration associated with this Graphics2D.

 o setComposite
public abstract void setComposite(Composite comp)
Sets the Composite in the current graphics state. Composite is used in all drawing methods such as drawImage, drawString, draw, and fill. It specifies how new pixels are to be combined with the existing pixels on the graphics device in the rendering process.

Parameters:
comp - The Composite object to be used for drawing.
See Also:
setXORMode, setPaintMode, AlphaComposite
 o setPaint
public abstract void setPaint(Paint paint)
Sets the Paint in the current graphics state.

Parameters:
paint - The Paint object to be used to generate color in the rendering process.
See Also:
setColor, GradientPaint, TexturePaint
 o setStroke
public abstract void setStroke(Stroke s)
Sets the Stroke in the current graphics state.

Parameters:
s - The Stroke object to be used to stroke a Shape in the rendering process.
See Also:
BasicStroke
 o setRenderingHints
public abstract void setRenderingHints(int hintCategory,
                                       int hintValue)
Sets the preferences for the rendering algorithms. Hint categories include controls for rendering quality and overall time/quality trade-off in the rendering process.

Parameters:
hintCategory - The category of hint to be set. Possible values are ANTIALIASING and RENDERING.
hintValue - The value indicating preferences for the specified hint category. Possible values for the ANTIALIASING category are ANTIALIAS_ON, ANTIALIAS_OFF, ANTIALIAS_DEFAULT. Possible values for the RENDERING hint are RENDER_SPEED, RENDER_QUALITY, RENDER_DEFAULT.
See Also:
ANTIALIASING, RENDERING, ANTIALIAS_ON, ANTIALIAS_OFF, ANTIALIAS_DEFAULT, RENDER_SPEED, RENDER_QUALITY, RENDER_DEFAULT
 o getRenderingHints
public abstract int getRenderingHints(int hintCategory)
Returns the preferences for the rendering algorithms.

Parameters:
hintCategory - The category of hint to be set. Possible values are ANTIALIASING and RENDERING.
Returns:
The preferences for rendering algorithms. Possible values for the ANTIALIASING category are ANTIALIAS_ON, ANTIALIAS_OFF, ANTIALIAS_DEFAULT. Possible values for the RENDERING hint are RENDER_SPEED, RENDER_QUALITY, RENDER_DEFAULT.
See Also:
ANTIALIASING, RENDERING, ANTIALIAS_ON, ANTIALIAS_OFF, ANTIALIAS_DEFAULT, RENDER_SPEED, RENDER_QUALITY, RENDER_DEFAULT
 o transform
public abstract void transform(AffineTransform Tx)
Composes a Transform object with the transform in this Graphics2D according to the rule last-specified-first-applied. If the currrent transform is Cx, the result of composition with Tx is a new transform Cx'. Cx' becomes the current transform for this Graphics2D. Transforming a point p by the updated transform Cx' is equivalent to first transforming p by Tx and then transforming the result by the original transform Cx. In other words, Cx'(p) = Cx(Tx(p)). A copy of the Tx is made, if necessary, so further modifications to Tx do not affect rendering.

Parameters:
Tx - The Transform object to be composed with the current transform.
See Also:
setTransform, TransformChain, AffineTransform
 o setTransform
public abstract void setTransform(AffineTransform Tx)
Sets the Transform in the current graphics state.

Parameters:
Tx - The Transform object to be used in the rendering process.
See Also:
transform, TransformChain, AffineTransform
 o getTransform
public abstract AffineTransform getTransform()
Returns the current Transform in the Graphics2D state.

See Also:
transform, setTransform
 o getPaint
public abstract Paint getPaint()
Returns the current Paint in the Graphics2D state.

See Also:
setPaint, setColor
 o getComposite
public abstract Composite getComposite()
Returns the current Composite in the Graphics2D state.

See Also:
setComposite
 o setBackground
public abstract void setBackground(Color color)
Sets the background color in this context used for clearing a region. When Graphics2D is constructed for a component, the backgroung color is inherited from the component. Setting the background color in the Graphics2D context only affects the subsequent clearRect() calls and not the background color of the component. To change the background of the component, use appropriate methods of the component.

Parameters:
color - The background color that should be used in subsequent calls to clearRect().
See Also:
getBackground, Graphics.clearRect()
 o getBackground
public abstract Color getBackground()
Returns the background color used for clearing a region.

See Also:
setBackground
 o getStroke
public abstract Stroke getStroke()
Returns the current Stroke in the Graphics2D state.

See Also:
setStroke
 o clip
public abstract void clip(Shape s)
Intersects the current clip with the interior of the specified Shape and sets the current clip to the resulting intersection. The indicated shape is transformed with the current transform in the Graphics2D state before being intersected with the current clip. This method is used to make the current clip smaller. To make the clip larger, use any setClip method.

Parameters:
s - The Shape to be intersected with the current clip.

All Packages  Class Hierarchy  This Package  Previous  Next  Index  

Submit a bug or feature