Java 2D Strokes, Paint, Transforms, Clipping and Transparency
The Graphics2D pipeline settings in depth: BasicStroke widths, caps, joins, miter limits and dashes; color, gradient and texture paints; affine transforms and their order; clipping with shapes and text outlines; and alpha compositing with the twelve Porter-Duff rules.
kvi5hnuCode Sprout team member21 min readOn this page
The previous article followed a shape through the Java 2D pipeline: stroke, transform, clip, fill, compose. Each stage is controlled by one setting of the Graphics2D context. This article goes through them one at a time: what a Stroke does to an outline, which kinds of Paint exist, how affine transforms combine, how to clip without breaking the caller's clip, and how transparent pixels are blended.
Strokes
draw(shape) traces the outline with the current stroke, an object implementing the Stroke interface. Its single method, createStrokedShape(Shape), turns the outline into the area the pen covers, which the pipeline then fills. The JDK provides one implementation, BasicStroke:
g2.setStroke(new BasicStroke(10f)); // 10 units wide
g2.draw(new Line2D.Double(20, 20, 200, 80));
The default stroke of a fresh context is new BasicStroke(): width 1, square caps, miter joins, miter limit 10, no dashes. A width of 0 is allowed and means "the thinnest line the device can draw", a hairline that stays one pixel wide whatever the transform.
The width is in user units and, like everything else, passes through the transform. A 1-unit stroke on a context scaled by 3 is 3 pixels wide (see the transform section). The stroke is centered on the outline: half of it lies inside the shape and half outside.

End caps
The ends of an open path, and the ends of each dash, get one of three caps:
CAP_BUTT: the stroke ends flat at the end point.CAP_ROUND: a half circle with a diameter equal to the width is added.CAP_SQUARE: half a square is added, so the stroke extends half its width beyond the end point.
The demo prints the bounds of the stroked outline for each cap: the butt cap ends exactly at x = 6 and 18, the other two reach 2 units (half of the width 4) farther.
Joins and the miter limit
Where two segments meet, the outer edges have to be connected by a join:
JOIN_MITER: the outer edges are extended until they meet in a point.JOIN_ROUND: the corner is rounded with a circle of the stroke's diameter.JOIN_BEVEL: the corner is cut off by a straight line across the ends of the two outer edges.
For sharp angles, a miter becomes a long spike: its length is the stroke width divided by sin(θ/2), where θ is the angle between the segments. The miter limit caps this. When the ratio of the miter length to the stroke width exceeds the limit, the join is drawn as a bevel. The default limit of 10 bevels every corner sharper than about 11.5 degrees (2·asin(1/10)). In the demo, a corner of 8.97 degrees would need a miter 12.78 widths long: with the limit 10 it is beveled, and the outline stops just above the corner; with limit 15 the spike reaches 37 units above it.
g2.setStroke(new BasicStroke(10f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2.setStroke(new BasicStroke(10f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 15f));
Round joins and caps are the safest choice for thick polylines such as chart lines or freehand drawing; they never spike and never show gaps.
Dashes
A dash pattern is a float[] of alternating "on" and "off" lengths, in user units. The pattern repeats along the whole path, continuing around corners. The dash phase is an offset into the pattern at which the stroke starts: with phase 2, the path begins as if 2 units of the pattern had already been drawn.
float[] pattern = {10, 5, 2, 5}; // long dash, gap, dot, gap
g2.setStroke(new BasicStroke(2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f, pattern, 0f));
Each dash is a separate piece of stroke with its own two end caps. With square or round caps, every dash grows by the stroke width and the gaps shrink by the same amount; the demo's {4, 4} pattern drawn 2 units wide shows 6-pixel dashes and 2-pixel gaps with square caps. Use CAP_BUTT when the gaps must have the exact lengths in the pattern. Animating the phase makes the familiar "marching ants" selection outline.
A pattern must have at least one positive entry and no negative ones, or the constructor throws IllegalArgumentException.
BasicStroke is immutable; it has getters (getLineWidth, getEndCap, getLineJoin, getMiterLimit, getDashArray, getDashPhase) but no setters. You can also call createStrokedShape yourself, for example to hit-test whether the mouse is "on" a thick line, or to fill the outline of a line with a gradient.
Paint
fill, and the fill step of draw, color the pixels with the current paint, set with setPaint. A Paint computes a color for every pixel. Five implementations come with the JDK.
Color
Color implements Paint, so g2.setPaint(Color.RED) fills with one color. (setColor is the old Graphics method and does the same for colors.) A color may have an alpha component: new Color(255, 0, 0, 128) is half-transparent red.
GradientPaint
GradientPaint blends between two colors along a line from point p1 to point p2. Colors are constant along lines perpendicular to that line. Before p1 the paint uses the first color and after p2 the second, unless the cyclic flag is set: then the colors run back and forth forever.
g2.setPaint(new GradientPaint(p1, Color.RED, p2, Color.YELLOW));
g2.setPaint(new GradientPaint(p1, Color.RED, p2, Color.YELLOW, true)); // cyclic
The gradient lives in user space: the points do not move with the shape. To give each shape the same gradient, compute p1 and p2 from the shape's bounds.
LinearGradientPaint and RadialGradientPaint
Since Java 6, LinearGradientPaint and RadialGradientPaint (subclasses of MultipleGradientPaint) support any number of color stops at fractions between 0 and 1, like CSS gradients:
var sunset = new LinearGradientPaint(0, 0, 0, height,
new float[] {0f, 0.6f, 1f},
new Color[] {new Color(0x1E3A8A), new Color(0xF97316), new Color(0xFDE68A)});
var glow = new RadialGradientPaint(center, radius,
new float[] {0f, 1f}, new Color[] {Color.WHITE, new Color(0, 0, 0, 0)});
Fractions must increase strictly. A CycleMethod controls what happens outside the gradient: NO_CYCLE (extend the end colors, the default), REFLECT (mirror back and forth, what GradientPaint calls cyclic) and REPEAT (jump back to the first color). A radial gradient varies with the distance from a center; an optional focus point moves the place where the first color sits, which gives an off-center highlight like light on a sphere. There are also constructors that take a ColorSpaceType (SRGB or LINEAR_RGB interpolation) and an extra AffineTransform for the gradient. The demo prints the gray levels of each variant along a 40-pixel strip.
TexturePaint
TexturePaint tiles the plane with a BufferedImage. The anchor rectangle defines the first tile; it is repeated in all directions, and the image is scaled to fit each tile:
BufferedImage tile = ImageIO.read(Path.of("brick.png").toFile());
g2.setPaint(new TexturePaint(tile, new Rectangle2D.Double(0, 0, 32, 16)));
g2.fill(wall);
Like gradients, the tiles are fixed in user space, so the texture does not move when the shape moves; shift the anchor to move it. Images are covered in the next article.
Coordinate transformations
The transform maps user coordinates, the units your program thinks in, to device coordinates, pixels or printer dots. With it, a program can draw a floor plan in meters, a chart in data units or a clock face in degrees and let Graphics2D convert:
g2.scale(pixelsPerMeter, pixelsPerMeter);
g2.draw(new Line2D.Double(0, 0, 3.5, 0)); // 3.5 meters long
There are four fundamental transformations:
- Scaling multiplies all distances from the origin, possibly by different factors in x and y. A negative factor mirrors.
- Rotation turns all points around the origin. A positive angle (in radians) turns the positive x axis toward the positive y axis, which on screen, with y pointing down, is clockwise.
- Translation moves all points by a fixed amount.
- Shear keeps one axis fixed and slides lines parallel to it in proportion to their distance from it, turning rectangles into parallelograms. The demo's
shear(0.5, 0)moves (0, 10) to (5, 10) and leaves the x axis alone.
Graphics2D has methods for each (scale, rotate, translate, shear), plus rotate(angle, x, y) for rotating around a point.
Order matters
The methods do not replace the transform; they compose the new transformation with the existing one, and the composition works backwards: the transformation specified last is applied to points first. Think of each call as changing the coordinate system that later drawing calls use.
g2.translate(100, 50);
g2.rotate(Math.PI / 2);
g2.scale(2, 2);
g2.draw(shape); // shape is scaled, then rotated, then translated
The demo applies these three calls to the point (10, 0): scaling gives (20, 0), rotating (0, 20), translating (100, 70). Issuing the same calls in the reverse order sends the point to (-100, 220). Only some pairs commute, such as a rotation and a uniform scaling.
The classic consequence: rotating around a point (x, y) is translate to (x, y), rotate, translate back:
g2.translate(x, y);
g2.rotate(angle);
g2.translate(-x, -y); // applied first: moves (x, y) to the origin
which is exactly what rotate(angle, x, y) does; the demo confirms that both produce the same matrix.
AffineTransform
All four transformations and their combinations are affine: they map lines to lines and keep parallel lines parallel. Each is described by a 3 by 3 matrix whose last row is fixed, so six numbers suffice:
| x' | | m00 m01 m02 | | x | x' = m00·x + m01·y + m02
| y' | = | m10 m11 m12 | · | y | y' = m10·x + m11·y + m12
| 1 | | 0 0 1 | | 1 |
The class java.awt.geom.AffineTransform holds such a matrix. Create one with the constructor AffineTransform(m00, m10, m01, m11, m02, m12) (note the column order), with a factory method (getRotateInstance, getScaleInstance, getTranslateInstance, getShearInstance), or start with the identity and call the same translate, rotate, scale and shear methods as on Graphics2D. setToRotation, setToScale and the like reset an existing transform to a basic one, and getMatrix(double[]) reads the six values back. Since Java 6, rotate and getRotateInstance also accept a direction vector, and quadrantRotate rotates by exact multiples of 90 degrees, without the rounding errors of Math.cos(Math.PI / 2).
Two methods combine transforms explicitly. t.concatenate(u) makes u apply before t (it is what Graphics2D.transform(u) does); t.preConcatenate(u) makes u apply after t. The demo applies a translation by 1 to a scaling by 2 both ways: (1, 0) goes to (4, 0) or (3, 0).
An AffineTransform is also a calculator:
transform(point, result)maps points;transform(double[] src, ..., double[] dst, ..., n)maps many at once.deltaTransformmaps vectors, ignoring the translation.inverseTransform(point, result)andcreateInverse()go from device back to user coordinates. Interactive programs need this: a mouse click arrives in device coordinates, and to find which shape was clicked in a zoomed view, you invert the view's transform. A transform that collapses the plane (scale 0) has no inverse and throwsNoninvertibleTransformException.createTransformedShape(shape)returns a transformed copy of any shape.getType()returns flags such asTYPE_TRANSLATION,TYPE_UNIFORM_SCALEandTYPE_MASK_ROTATION, which renderers use to choose fast paths.
Transforming the graphics context
g2.transform(t) composes t with the current transform. g2.setTransform(t) replaces it, and that is almost always a bug. The context you receive already has a transform: the printing system puts a landscape rotation and a scale from points to printer dots there, and on a HiDPI display (Java 9 and later, JEP 263) Swing installs a scale of 1.5 or 2 so that a 100-unit component covers 150 or 200 physical pixels. Setting a new transform throws that away, and your drawing comes out tiny or in the wrong place. To apply a transform temporarily, save and restore it:
AffineTransform saved = g2.getTransform();
g2.rotate(angle, cx, cy);
g2.draw(hand);
g2.setTransform(saved); // restoring a saved transform is fine
or work on a copy from g2.create().
Remember that strokes are transformed too: the demo draws a square with a 1-unit stroke under scale(3, 3) and gets 3-pixel lines. If the shape should grow but the line should not, transform the shape with createTransformedShape and draw it with the original transform, as the demo does for the inner square, or use a hairline (width 0) stroke.
Clipping
The clip limits drawing to the inside of a shape. Every pixel outside the clip is left untouched.
g2.clip(clipShape); // intersect the current clip with clipShape
g2.draw(shape);
As with transforms, there is a replacing method, setClip(shape), inherited from Graphics, and the combining one, clip(shape), which intersects. Use clip. The context you get in paintComponent is clipped to the region being repainted, a printer context to the printable area of the page; replacing the clip can paint over neighboring components or into the margins. setClip(null) removes the clip completely. To clip temporarily, save and restore:
Shape saved = g2.getClip();
g2.clip(circle);
drawPicture(g2);
g2.setClip(saved);
getClip() returns the clip as a Shape in user coordinates and getClipBounds() its bounding rectangle, which can be larger than the actual clip because the clip is converted to device pixels. hitClip(x, y, w, h) quickly tests whether a rectangle might be visible: components use it to skip drawing what lies outside the repainted region.
Any shape can be a clip: an ellipse for a round avatar picture, an Area with holes, or the outline of text. For text, get the glyph outlines from a TextLayout (or Font.createGlyphVector(...).getOutline()):
FontRenderContext context = g2.getFontRenderContext();
var layout = new TextLayout("Hello", new Font(Font.SERIF, Font.BOLD, 96), context);
Shape outline = layout.getOutline(AffineTransform.getTranslateInstance(20, 120));
g2.clip(outline);
// everything drawn now appears only inside the letters
The outline is positioned with its baseline at the origin, so the transform passed to getOutline moves it to where it should appear. The font render context describes the device (resolution, antialiasing, fractional metrics), because the same text has slightly different shapes on screen and on a printer. TextLayout also reports getAdvance() (width), getAscent(), getDescent() and getLeading(), and getBounds() gives the tight box around the glyphs.
Clipping with curved shapes is subject to antialiasing in a limited way: OpenJDK's clip is pixel-based, so a curved clip has hard, jagged edges even with antialiasing on. For a smooth-edged circular picture, fill a circle in an ARGB image and composite the picture into it with SRC_IN instead.
Transparency and composition
In the last stage, each new pixel (the source) is combined with the pixel already on the surface (the destination). Colors in Java 2D can carry an alpha value, the opacity, from 0 (fully transparent) to 1 (fully opaque). Normally a partly transparent source is blended over the destination, so the old picture shows through.
The blending rule is the composite, set with setComposite. The standard implementation, AlphaComposite, implements the twelve rules that Thomas Porter and Tom Duff described in their 1984 paper "Compositing Digital Images". The idea: treat a pixel's alpha as the fraction of the pixel its color covers. Where source and destination overlap, a rule decides whether the source, the destination or neither survives in each of these cases: only the source covers, only the destination covers, or both cover. Formally, each rule picks two factors, Fs for the source and Fd for the destination, and the result is
result = source · Fs + destination · Fd (colors premultiplied by alpha; same formula for alpha)
| Rule | Fs | Fd | Effect |
|---|---|---|---|
CLEAR | 0 | 0 | Erase to transparent. |
SRC | 1 | 0 | Source replaces destination, alpha included. |
DST | 0 | 1 | Destination unchanged. |
SRC_OVER | 1 | 1 - αs | Source blended over destination: the default. |
DST_OVER | 1 - αd | 1 | Source painted behind the destination. |
SRC_IN | αd | 0 | Source only where the destination is, a mask. |
DST_IN | 0 | αs | Destination kept only where the source is. |
SRC_OUT | 1 - αd | 0 | Source only where the destination is not. |
DST_OUT | 0 | 1 - αs | Destination erased where the source is. |
SRC_ATOP | αd | 1 - αs | Source over destination, but only inside it. |
DST_ATOP | 1 - αd | αs | Destination over source, only inside the source. |
XOR | 1 - αd | 1 - αs | Each only where the other is not. |
Most programs need SRC_OVER and nothing else. SRC is useful to write pixels including their alpha (for example to clear an area of an ARGB image to transparent without blending). The IN and OUT rules implement masks: draw a mask shape, then draw a picture with SRC_IN, and the picture appears only inside the mask, with soft antialiased edges. DST_OUT works as an eraser.
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
g2.setPaint(Color.BLUE);
g2.fill(rectangle); // blue at 50% opacity over what was there
The second argument of getInstance is an extra alpha that multiplies the alpha of every source pixel, which makes it the easy way to draw anything, including images and text, semi-transparent. Constants such as AlphaComposite.SrcOver and AlphaComposite.Clear hold the instances without extra alpha, and derive(alpha) or derive(rule) (Java 6) produce variations.
The demo composes a blue source with alpha 0.75 onto an opaque red destination under each rule and prints three pixels: where only the source was drawn, where both overlap, and where only the destination exists. SRC_OVER gives 75% blue mixed with 25% red where they overlap; DST_OVER leaves the red in front; SRC_ATOP blends but leaves the source-only pixel transparent; XOR keeps the source-only pixel and only a 25% red where both were.
The destination needs an alpha channel
Half of the rules depend on the destination's alpha. A window on the screen, and an image of type TYPE_INT_RGB, has no alpha channel: every pixel counts as opaque, and the composed alpha is thrown away. The demo shows this: on an RGB image, SRC with extra alpha 0.5 does not produce a translucent pixel but plain blue. To experiment with the rules, or to build a picture with transparent regions, compose into a BufferedImage of type TYPE_INT_ARGB and then draw the image onto the screen, which is what the listing below does.
Composite is an interface, so other blend modes (multiply, screen and so on) can be implemented with a CompositeContext that works on rasters; the JDK itself ships only AlphaComposite. (Graphics.setXORMode(color), the old way to draw rubber-band outlines that disappear when drawn twice, still exists but has nothing to do with the Porter-Duff XOR rule.)
A graphics lab
This program has three tabs. Strokes draws two joined segments with a thick stroke; drag the three handles, and choose caps, joins and an SOS dash pattern. Make the angle very sharp with miter joins to watch the miter limit kick in. Composition draws a red ellipse, then a blue rectangle with the chosen Porter-Duff rule and source alpha, in an ARGB image over a checkerboard, so transparent results are visible. Clipping draws rays clipped by the outline of a word you type.
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.font.TextLayout;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public final class GraphicsLab extends JFrame {
private static final long serialVersionUID = 1L;
/** Two joined segments with draggable end points, drawn with the chosen stroke. */
static final class StrokePanel extends JComponent {
private static final long serialVersionUID = 1L;
private final transient Point2D[] points = {
new Point2D.Double(200, 80), new Point2D.Double(100, 250), new Point2D.Double(300, 250)};
private int dragged = -1;
private int cap = BasicStroke.CAP_BUTT;
private int join = BasicStroke.JOIN_MITER;
private boolean dashed;
StrokePanel() {
setPreferredSize(new Dimension(420, 320));
var mouse = new MouseAdapter() {
@Override public void mousePressed(MouseEvent e) {
for (int i = 0; i < points.length; i++)
if (points[i].distance(e.getPoint()) < 8) dragged = i;
}
@Override public void mouseReleased(MouseEvent e) { dragged = -1; }
@Override public void mouseDragged(MouseEvent e) {
if (dragged >= 0) { points[dragged] = e.getPoint(); repaint(); }
}
};
addMouseListener(mouse);
addMouseMotionListener(mouse);
}
void setCap(int c) { cap = c; repaint(); }
void setJoin(int j) { join = j; repaint(); }
void setDashed(boolean d) { dashed = d; repaint(); }
@Override protected void paintComponent(Graphics g) {
var g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
var path = new Path2D.Double();
path.moveTo(points[0].getX(), points[0].getY());
for (int i = 1; i < points.length; i++) path.lineTo(points[i].getX(), points[i].getY());
float[] sos = {10, 10, 10, 10, 10, 30, 30, 10, 30, 10, 30, 30, 10, 10, 10, 10, 10, 60};
var stroke = dashed ? new BasicStroke(16f, cap, join, 10f, sos, 0) : new BasicStroke(16f, cap, join);
g2.setPaint(new Color(0x93C5FD));
g2.setStroke(stroke);
g2.draw(path);
g2.setStroke(new BasicStroke(1f)); // the geometric path on top
g2.setPaint(Color.RED);
g2.draw(path);
g2.setPaint(Color.BLACK);
for (Point2D p : points) g2.draw(new Rectangle2D.Double(p.getX() - 4, p.getY() - 4, 8, 8));
g2.dispose();
}
}
/** A red ellipse (destination) and a blue rectangle (source) combined with a Porter-Duff rule. */
static final class CompositePanel extends JComponent {
private static final long serialVersionUID = 1L;
private int rule = AlphaComposite.SRC_OVER;
private float alpha = 0.75f;
CompositePanel() { setPreferredSize(new Dimension(420, 320)); }
void setRule(int r) { rule = r; repaint(); }
void setAlpha(float a) { alpha = a; repaint(); }
@Override protected void paintComponent(Graphics g) {
var g2 = (Graphics2D) g.create();
g2.setPaint(new TexturePaint(checkerboard(), new Rectangle(0, 0, 20, 20)));
g2.fillRect(0, 0, getWidth(), getHeight()); // shows where pixels end up transparent
// compose in an image with an alpha channel; the screen usually has none
var image = new BufferedImage(Math.max(1, getWidth()), Math.max(1, getHeight()), BufferedImage.TYPE_INT_ARGB);
Graphics2D gi = image.createGraphics();
gi.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
gi.setPaint(Color.RED);
gi.fill(new Ellipse2D.Double(60, 50, 200, 150));
gi.setComposite(AlphaComposite.getInstance(rule, alpha));
gi.setPaint(Color.BLUE);
gi.fill(new Rectangle2D.Double(140, 120, 200, 150));
gi.dispose();
g2.drawImage(image, 0, 0, null);
g2.dispose();
}
private static BufferedImage checkerboard() {
var tile = new BufferedImage(2, 2, BufferedImage.TYPE_INT_RGB);
tile.setRGB(0, 0, 0xFFFFFF); tile.setRGB(1, 1, 0xFFFFFF);
tile.setRGB(1, 0, 0xDDDDDD); tile.setRGB(0, 1, 0xDDDDDD);
return tile;
}
}
/** Rays from a corner, clipped by the outline of a word. */
static final class ClipPanel extends JComponent {
private static final long serialVersionUID = 1L;
private String word = "Java 2D";
ClipPanel() { setPreferredSize(new Dimension(420, 320)); }
void setWord(String w) { word = w.isBlank() ? " " : w; repaint(); }
@Override protected void paintComponent(Graphics g) {
var g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
var layout = new TextLayout(word, new Font(Font.SERIF, Font.BOLD, 96), g2.getFontRenderContext());
Rectangle2D bounds = layout.getBounds();
// the outline starts at the baseline origin; move it to the center of the panel
double x = (getWidth() - bounds.getWidth()) / 2 - bounds.getX();
double y = (getHeight() - bounds.getHeight()) / 2 - bounds.getY();
Shape outline = layout.getOutline(AffineTransform.getTranslateInstance(x, y));
Shape oldClip = g2.getClip();
g2.clip(outline); // intersect, never replace
g2.setPaint(new GradientPaint(0, 0, new Color(0x1D4ED8), getWidth(), getHeight(), new Color(0xDB2777)));
for (int i = 0; i <= 60; i++) {
double angle = Math.PI / 2 * i / 60;
g2.draw(new Line2D.Double(0, 0, 1000 * Math.cos(angle), 1000 * Math.sin(angle)));
}
g2.setClip(oldClip); // restore for the outline
g2.setPaint(Color.GRAY);
g2.draw(outline);
g2.dispose();
}
}
record Choice(String label, int value) {
@Override public String toString() { return label; }
}
public GraphicsLab() {
super("Graphics Lab");
var tabs = new JTabbedPane();
var strokes = new StrokePanel();
var caps = new JComboBox<>(new Choice[] {new Choice("Butt cap", BasicStroke.CAP_BUTT),
new Choice("Round cap", BasicStroke.CAP_ROUND), new Choice("Square cap", BasicStroke.CAP_SQUARE)});
caps.addActionListener(_ -> strokes.setCap(caps.getItemAt(caps.getSelectedIndex()).value()));
var joins = new JComboBox<>(new Choice[] {new Choice("Miter join", BasicStroke.JOIN_MITER),
new Choice("Round join", BasicStroke.JOIN_ROUND), new Choice("Bevel join", BasicStroke.JOIN_BEVEL)});
joins.addActionListener(_ -> strokes.setJoin(joins.getItemAt(joins.getSelectedIndex()).value()));
var dashed = new JCheckBox("Dashed (SOS)");
dashed.addActionListener(_ -> strokes.setDashed(dashed.isSelected()));
var strokeControls = new JPanel();
strokeControls.add(caps);
strokeControls.add(joins);
strokeControls.add(dashed);
tabs.addTab("Strokes", panel(strokeControls, strokes));
var composite = new CompositePanel();
String[] names = {"CLEAR", "SRC", "DST", "SRC_OVER", "DST_OVER", "SRC_IN", "SRC_OUT",
"DST_IN", "DST_OUT", "SRC_ATOP", "DST_ATOP", "XOR"};
var rules = new Choice[names.length];
for (int i = 0; i < names.length; i++) {
try {
rules[i] = new Choice(names[i], AlphaComposite.class.getField(names[i]).getInt(null));
} catch (ReflectiveOperationException e) {
throw new IllegalStateException(e);
}
}
var ruleBox = new JComboBox<>(rules);
ruleBox.setSelectedIndex(3);
ruleBox.addActionListener(_ -> composite.setRule(ruleBox.getItemAt(ruleBox.getSelectedIndex()).value()));
var alpha = new JSlider(0, 100, 75);
alpha.addChangeListener(_ -> composite.setAlpha(alpha.getValue() / 100f));
var compositeControls = new JPanel();
compositeControls.add(ruleBox);
compositeControls.add(new JLabel("Source alpha"));
compositeControls.add(alpha);
tabs.addTab("Composition", panel(compositeControls, composite));
var clip = new ClipPanel();
var word = new JTextField("Java 2D", 12);
word.addActionListener(_ -> clip.setWord(word.getText()));
var clipControls = new JPanel();
clipControls.add(new JLabel("Clip text (press Enter):"));
clipControls.add(word);
tabs.addTab("Clipping", panel(clipControls, clip));
add(tabs);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationByPlatform(true);
}
private static JPanel panel(JComponent north, JComponent center) {
var p = new JPanel(new BorderLayout());
p.add(north, BorderLayout.NORTH);
p.add(center, BorderLayout.CENTER);
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new GraphicsLab().setVisible(true));
}
}
In the composition tab, compare DST_IN and DST_OUT while moving the slider: neither draws any blue, but the source alpha decides how much of the red survives. The clipping tab saves and restores the clip so that the outline of the letters can be drawn on top without being clipped itself.
The program
The demo renders into small grayscale and ARGB images in headless mode and prints the pixels: # for white, . for black, + for in between, and gray levels as digits from 0 (black) to 9 (white). Antialiasing stays off so the output is the same on every platform.
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.util.Locale;
public class Solution {
public static void main(String[] args) throws Exception {
System.setProperty("java.awt.headless", "true");
Locale.setDefault(Locale.US);
strokes();
paints();
transforms();
clipping();
composition();
}
/** Prints a gray image as characters: '#' white, '.' black, '+' anything in between. */
static void print(BufferedImage image) {
for (int y = 0; y < image.getHeight(); y++) {
var sb = new StringBuilder(" ");
for (int x = 0; x < image.getWidth(); x++) {
int v = image.getRaster().getSample(x, y, 0);
sb.append(v == 255 ? '#' : v == 0 ? '.' : '+');
}
System.out.println(sb);
}
}
static BufferedImage gray(int w, int h) { return new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY); }
static String fmt(Rectangle2D r) {
return "x %.2f..%.2f, y %.2f..%.2f".formatted(r.getMinX(), r.getMaxX(), r.getMinY(), r.getMaxY());
}
static void strokes() {
System.out.println("== End caps on a line from x = 6 to x = 18, 4 units wide ==");
String[] capNames = {"CAP_BUTT", "CAP_ROUND", "CAP_SQUARE"};
var line = new Line2D.Double(6, 3, 18, 3);
for (int cap = 0; cap < 3; cap++) {
var stroke = new BasicStroke(4f, cap, BasicStroke.JOIN_MITER);
System.out.printf("%-10s outline covers %s%n", capNames[cap], fmt(stroke.createStrokedShape(line).getBounds2D()));
var image = gray(24, 6);
Graphics2D g = image.createGraphics();
g.setColor(Color.WHITE);
g.setStroke(stroke);
g.draw(line);
g.dispose();
print(image);
}
System.out.println();
System.out.println("== Joins: a 6-unit stroke along two segments meeting at (20, 5) ==");
var corner = new Path2D.Double();
corner.moveTo(0, 20);
corner.lineTo(20, 5);
corner.lineTo(40, 20);
String[] joinNames = {"JOIN_MITER", "JOIN_ROUND", "JOIN_BEVEL"};
for (int join = 0; join < 3; join++) {
var stroke = new BasicStroke(6f, BasicStroke.CAP_BUTT, join);
System.out.printf(" %-10s top of the outline at y = %.2f%n", joinNames[join],
stroke.createStrokedShape(corner).getBounds2D().getMinY());
}
// an acute corner: the miter would be long, so the miter limit turns it into a bevel
var sharp = new Path2D.Double();
sharp.moveTo(0, 60);
sharp.lineTo(20, 0);
sharp.lineTo(10, 60);
double angle = Math.toDegrees(Math.atan2(60, -20) - Math.atan2(60, -10));
System.out.printf("acute corner of %.2f degrees at (20, 0): the miter would be %.2f stroke widths long%n",
angle, 1 / Math.sin(Math.toRadians(angle) / 2));
for (float limit : new float[] {10f, 15f}) {
var stroke = new BasicStroke(6f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, limit);
System.out.printf(" miter limit %4.1f: top of the outline at y = %.2f%n", limit,
stroke.createStrokedShape(sharp).getBounds2D().getMinY());
}
System.out.printf(" default limit 10 cuts off corners sharper than %.2f degrees%n",
Math.toDegrees(2 * Math.asin(1 / 10.0)));
System.out.println();
System.out.println("== Dashes: pattern {4, 4} on a 30-unit line, 2 units wide ==");
var dashLine = new Line2D.Double(0, 1, 30, 1);
for (float phase : new float[] {0, 2}) {
for (int cap : new int[] {BasicStroke.CAP_BUTT, BasicStroke.CAP_SQUARE}) {
var stroke = new BasicStroke(2f, cap, BasicStroke.JOIN_MITER, 10f, new float[] {4, 4}, phase);
var image = gray(32, 2);
Graphics2D g = image.createGraphics();
g.setColor(Color.WHITE);
g.setStroke(stroke);
g.draw(dashLine);
g.dispose();
var sb = new StringBuilder();
for (int x = 0; x < 32; x++) sb.append(image.getRaster().getSample(x, 1, 0) > 0 ? '#' : '.');
System.out.printf(" phase %.0f, %-10s %s%n", phase, cap == BasicStroke.CAP_BUTT ? "CAP_BUTT" : "CAP_SQUARE", sb);
}
}
}
/** Fills a w x 1 strip with the paint and prints the gray levels (0-9). */
static String strip(Paint paint, int w) {
var image = gray(w, 1);
Graphics2D g = image.createGraphics();
g.setPaint(paint);
g.fillRect(0, 0, w, 1);
g.dispose();
var sb = new StringBuilder();
for (int x = 0; x < w; x++) sb.append(image.getRaster().getSample(x, 0, 0) * 9 / 255);
return sb.toString();
}
static void paints() {
System.out.println();
System.out.println("== Paints: gray level 0 (black) to 9 (white) across 40 pixels ==");
Point2D p1 = new Point2D.Float(10, 0), p2 = new Point2D.Float(20, 0);
System.out.println(" black at x = 10, white at x = 20:");
System.out.println(" GradientPaint " + strip(new GradientPaint(p1, Color.BLACK, p2, Color.WHITE), 40));
System.out.println(" GradientPaint cyclic " + strip(new GradientPaint(p1, Color.BLACK, p2, Color.WHITE, true), 40));
float[] fractions = {0f, 1f};
Color[] colors = {Color.BLACK, Color.WHITE};
for (var cycle : MultipleGradientPaint.CycleMethod.values())
System.out.printf(" Linear %-17s %s%n", cycle,
strip(new LinearGradientPaint(p1, p2, fractions, colors, cycle), 40));
var stops = new LinearGradientPaint(0, 0, 40, 0, new float[] {0f, 0.25f, 0.5f, 1f},
new Color[] {Color.BLACK, Color.WHITE, Color.BLACK, Color.WHITE});
System.out.println(" Linear, four stops " + strip(stops, 40));
var radial = new RadialGradientPaint(new Point2D.Float(10, 5), 10f, new float[] {0f, 1f},
new Color[] {Color.WHITE, Color.BLACK});
var image = gray(21, 11);
Graphics2D g = image.createGraphics();
g.setPaint(radial);
g.fillRect(0, 0, 21, 11);
g.dispose();
System.out.println("RadialGradientPaint, white center, radius 10:");
for (int y = 0; y < 11; y += 2) {
var sb = new StringBuilder(" ");
for (int x = 0; x < 21; x++) sb.append(image.getRaster().getSample(x, y, 0) * 9 / 255);
System.out.println(sb);
}
var tile = gray(2, 2); // a 2 x 2 checkerboard tile
tile.getRaster().setSample(0, 0, 0, 255);
tile.getRaster().setSample(1, 1, 0, 255);
image = gray(16, 4);
g = image.createGraphics();
g.setPaint(new TexturePaint(tile, new Rectangle2D.Double(1, 0, 4, 2))); // tile scaled to 4 x 2
g.fill(new Ellipse2D.Double(0, 0, 16, 4));
g.dispose();
System.out.println("TexturePaint, 2 x 2 tile anchored at (1, 0) and stretched to 4 x 2, filling an ellipse:");
print(image);
}
static void transforms() {
System.out.println();
System.out.println("== Affine transforms ==");
var t = new AffineTransform();
t.translate(100, 50); // applied last
t.rotate(Math.PI / 2); // applied second
t.scale(2, 2); // applied first
Point2D p = new Point2D.Double(10, 0);
System.out.println("translate(100, 50); rotate(90 deg); scale(2, 2) maps (10, 0) to " + pt(t.transform(p, null)));
var u = new AffineTransform();
u.scale(2, 2);
u.rotate(Math.PI / 2);
u.translate(100, 50);
System.out.println("the same calls in reverse order map it to " + pt(u.transform(p, null)));
System.out.println("matrix [m00 m10 m01 m11 m02 m12] = " + matrix(t));
var around = AffineTransform.getRotateInstance(Math.PI / 2, 5, 5);
var manual = AffineTransform.getTranslateInstance(5, 5);
manual.rotate(Math.PI / 2);
manual.translate(-5, -5);
System.out.println("rotate about (5, 5) moves (10, 5) to " + pt(around.transform(new Point2D.Double(10, 5), null))
+ "; same as translate-rotate-translate? " + around.equals(manual));
var shear = AffineTransform.getShearInstance(0.5, 0);
System.out.println("shear(0.5, 0) moves (0, 10) to " + pt(shear.transform(new Point2D.Double(0, 10), null))
+ " and keeps (10, 0) at " + pt(shear.transform(new Point2D.Double(10, 0), null)));
var view = AffineTransform.getTranslateInstance(40, 30);
view.scale(4, 4); // a zoomed view, 4 pixels per unit
Point2D mouse = new Point2D.Double(60, 70);
try {
System.out.println("mouse at device " + pt(mouse) + " is user point " + pt(view.inverseTransform(mouse, null)));
} catch (NoninvertibleTransformException e) {
System.out.println("cannot invert");
}
Point2D delta = view.deltaTransform(new Point2D.Double(1, 1), null);
System.out.println("deltaTransform ignores translation: (1, 1) -> " + pt(delta));
System.out.println("type flags of the view: translation " + ((view.getType() & AffineTransform.TYPE_TRANSLATION) != 0)
+ ", uniform scale " + ((view.getType() & AffineTransform.TYPE_UNIFORM_SCALE) != 0)
+ ", rotation " + ((view.getType() & AffineTransform.TYPE_MASK_ROTATION) != 0));
var a = AffineTransform.getScaleInstance(2, 2);
a.concatenate(AffineTransform.getTranslateInstance(1, 0)); // translation applied first
var b = AffineTransform.getScaleInstance(2, 2);
b.preConcatenate(AffineTransform.getTranslateInstance(1, 0)); // translation applied last
System.out.println("concatenate: (1, 0) -> " + pt(a.transform(new Point2D.Double(1, 0), null))
+ ", preConcatenate: (1, 0) -> " + pt(b.transform(new Point2D.Double(1, 0), null)));
System.out.println("a square scaled by 3, drawn with a 1-unit stroke:");
var image = gray(14, 14);
Graphics2D g = image.createGraphics();
g.setColor(Color.WHITE);
g.scale(3, 3);
g.draw(new Rectangle2D.Double(0.5, 0.5, 3.5, 3.5));
Rectangle2D.Double inner = new Rectangle2D.Double(1.5, 1.5, 1.5, 1.5);
AffineTransform saved = g.getTransform();
g.setTransform(new AffineTransform()); // identity: 1-pixel stroke
g.draw(saved.createTransformedShape(inner));
g.setTransform(saved);
g.dispose();
print(image);
System.out.println("(outer: stroke scaled to 3 pixels; inner: shape transformed, stroke stays 1 pixel)");
}
static String pt(Point2D p) { return "(%.1f, %.1f)".formatted(p.getX() + 0.0, p.getY() + 0.0); }
static String matrix(AffineTransform t) {
double[] m = new double[6];
t.getMatrix(m);
var sb = new StringBuilder("[");
for (int i = 0; i < 6; i++) sb.append(i > 0 ? " " : "").append("%.1f".formatted(m[i] + 0.0));
return sb.append("]").toString();
}
static void clipping() {
System.out.println();
System.out.println("== Clipping ==");
var image = gray(24, 12);
Graphics2D g = image.createGraphics();
g.setColor(Color.WHITE);
g.clip(new Ellipse2D.Double(0, 0, 24, 12));
System.out.println("clip bounds after clip(ellipse): " + g.getClipBounds());
g.clip(new Rectangle(4, 0, 30, 12)); // intersects with the current clip
Shape clip = g.getClip();
System.out.println("after clip(rectangle): contains (2, 6)? " + clip.contains(2, 6)
+ ", (5, 6)? " + clip.contains(5, 6) + ", (23.5, 0.5)? " + clip.contains(23.5, 0.5));
for (int x = -12; x < 24; x += 3) g.draw(new Line2D.Double(x, 0, x + 12, 12)); // diagonal lines
Shape saved = g.getClip();
g.setClip(null); // no clip at all
g.drawLine(0, 11, 23, 11);
g.setClip(saved);
g.dispose();
print(image);
System.out.println("(diagonals clipped to ellipse and rectangle; bottom line drawn with the clip removed)");
}
static void composition() {
System.out.println();
System.out.println("== Porter-Duff rules: blue source (alpha 0.75) onto a red destination (alpha 1) ==");
String[] names = {"CLEAR", "SRC", "DST", "SRC_OVER", "DST_OVER", "SRC_IN", "SRC_OUT",
"DST_IN", "DST_OUT", "SRC_ATOP", "DST_ATOP", "XOR"};
System.out.printf(" %-9s %-17s %-17s %-17s%n", "rule", "source only", "both", "destination only");
for (String name : names) {
int rule;
try {
rule = AlphaComposite.class.getField(name).getInt(null);
} catch (ReflectiveOperationException e) {
throw new AssertionError(e);
}
// pixel 0: only the source; pixel 1: both; pixel 2: only the destination
var image = new BufferedImage(3, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.setColor(Color.RED);
g.fillRect(1, 0, 2, 1); // destination
g.setComposite(AlphaComposite.getInstance(rule, 0.75f));
g.setColor(Color.BLUE);
g.fillRect(0, 0, 2, 1); // source
g.dispose();
System.out.printf(" %-9s %-17s %-17s %-17s%n", name, argb(image.getRGB(0, 0)),
argb(image.getRGB(1, 0)), argb(image.getRGB(2, 0)));
}
System.out.println("(a = alpha 0-255; color components are not premultiplied)");
var c = AlphaComposite.SrcOver.derive(0.5f);
System.out.println("AlphaComposite.SrcOver.derive(0.5f): rule SRC_OVER " + (c.getRule() == AlphaComposite.SRC_OVER)
+ ", alpha " + c.getAlpha());
var image = new BufferedImage(2, 1, BufferedImage.TYPE_INT_RGB); // no alpha channel
Graphics2D g = image.createGraphics();
g.setColor(Color.RED);
g.fillRect(0, 0, 2, 1);
g.setColor(new Color(0, 0, 255, 128)); // translucent color, default SRC_OVER
g.fillRect(0, 0, 1, 1);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 0.5f));
g.setColor(Color.BLUE);
g.fillRect(1, 0, 1, 1);
g.dispose();
System.out.println("on an RGB image without alpha: translucent blue over red " + argb(image.getRGB(0, 0))
+ ", SRC at 0.5 " + argb(image.getRGB(1, 0)));
}
static String argb(int v) {
return "a%3d r%3d b%3d".formatted(v >>> 24, (v >> 16) & 255, v & 255);
}
}
== End caps on a line from x = 6 to x = 18, 4 units wide ==
CAP_BUTT outline covers x 6.00..18.00, y 1.00..5.00
........................
......############......
......############......
......############......
......############......
........................
CAP_ROUND outline covers x 4.00..20.00, y 1.00..5.00
........................
......############......
.....##############.....
....################....
.....##############.....
........................
CAP_SQUARE outline covers x 4.00..20.00, y 1.00..5.00
........................
....################....
....################....
....################....
....################....
........................
== Joins: a 6-unit stroke along two segments meeting at (20, 5) ==
JOIN_MITER top of the outline at y = 1.25
JOIN_ROUND top of the outline at y = 2.00
JOIN_BEVEL top of the outline at y = 2.60
acute corner of 8.97 degrees at (20, 0): the miter would be 12.78 stroke widths long
miter limit 10.0: top of the outline at y = -0.95
miter limit 15.0: top of the outline at y = -37.22
default limit 10 cuts off corners sharper than 11.48 degrees
== Dashes: pattern {4, 4} on a 30-unit line, 2 units wide ==
phase 0, CAP_BUTT ####....####....####....####....
phase 0, CAP_SQUARE #####..######..######..######...
phase 2, CAP_BUTT ##....####....####....####......
phase 2, CAP_SQUARE ###..######..######..######.....
== Paints: gray level 0 (black) to 9 (white) across 40 pixels ==
black at x = 10, white at x = 20:
GradientPaint 0000000000001234567889999999999999999999
GradientPaint cyclic 9876543210001234567888765432100012345678
Linear NO_CYCLE 0000000000001234567889999999999999999999
Linear REFLECT 9876543210001234567888765432100012345678
Linear REPEAT 0012345678001234567800123456780012345678
Linear, four stops 0012345678987654321000011223344455667788
RadialGradientPaint, white center, radius 10:
000112334444433211000
001223455666554322100
001234566787665432100
001234566787665432100
001223455666554322100
000112334444433211000
TexturePaint, 2 x 2 tile anchored at (1, 0) and stretched to 4 x 2, filling an ellipse:
......##..#.....
....##..##..##..
.###..##..##..##
....##..##..##..
== Affine transforms ==
translate(100, 50); rotate(90 deg); scale(2, 2) maps (10, 0) to (100.0, 70.0)
the same calls in reverse order map it to (-100.0, 220.0)
matrix [m00 m10 m01 m11 m02 m12] = [0.0 2.0 -2.0 0.0 100.0 50.0]
rotate about (5, 5) moves (10, 5) to (5.0, 10.0); same as translate-rotate-translate? true
shear(0.5, 0) moves (0, 10) to (5.0, 10.0) and keeps (10, 0) at (10.0, 0.0)
mouse at device (60.0, 70.0) is user point (5.0, 10.0)
deltaTransform ignores translation: (1, 1) -> (4.0, 4.0)
type flags of the view: translation true, uniform scale true, rotation false
concatenate: (1, 0) -> (4.0, 0.0), preConcatenate: (1, 0) -> (3.0, 0.0)
a square scaled by 3, drawn with a 1-unit stroke:
##############
##############
##############
###........###
###........###
###..#####.###
###..#...#.###
###..#...#.###
###..#...#.###
###..#####.###
###........###
##############
##############
##############
(outer: stroke scaled to 3 pixels; inner: shape transformed, stroke stays 1 pixel)
== Clipping ==
clip bounds after clip(ellipse): java.awt.Rectangle[x=0,y=0,width=24,height=12]
after clip(rectangle): contains (2, 6)? false, (5, 6)? true, (23.5, 0.5)? false
............#...........
....#..#..#..#..#.......
.....#..#..#..#..#..#...
......#..#..#..#..#..#..
....#..#..#..#..#..#..#.
.....#..#..#..#..#..#..#
......#..#..#..#..#..#..
....#..#..#..#..#..#..#.
.....#..#..#..#..#..#...
......#..#..#..#..#..#..
.......#..#..#..#..#....
########################
(diagonals clipped to ellipse and rectangle; bottom line drawn with the clip removed)
== Porter-Duff rules: blue source (alpha 0.75) onto a red destination (alpha 1) ==
rule source only both destination only
CLEAR a 0 r 0 b 0 a 0 r 0 b 0 a255 r255 b 0
SRC a191 r 0 b255 a191 r 0 b255 a255 r255 b 0
DST a 0 r 0 b 0 a255 r255 b 0 a255 r255 b 0
SRC_OVER a191 r 0 b255 a255 r 64 b191 a255 r255 b 0
DST_OVER a191 r 0 b255 a255 r255 b 0 a255 r255 b 0
SRC_IN a 0 r 0 b 0 a191 r 0 b255 a255 r255 b 0
SRC_OUT a191 r 0 b255 a 0 r 0 b 0 a255 r255 b 0
DST_IN a 0 r 0 b 0 a191 r255 b 0 a255 r255 b 0
DST_OUT a 0 r 0 b 0 a 64 r255 b 0 a255 r255 b 0
SRC_ATOP a 0 r 0 b 0 a255 r 64 b191 a255 r255 b 0
DST_ATOP a191 r 0 b255 a191 r255 b 0 a255 r255 b 0
XOR a191 r 0 b255 a 64 r255 b 0 a255 r255 b 0
(a = alpha 0-255; color components are not premultiplied)
AlphaComposite.SrcOver.derive(0.5f): rule SRC_OVER true, alpha 0.5
on an RGB image without alpha: translucent blue over red a255 r127 b128, SRC at 0.5 a255 r 0 b255
Points to notice:
- Round and square caps both reach 2 units beyond the end points; the round cap's corners are cut off in the picture.
- The miter join reaches highest (y = 1.25), the bevel lowest. At the 8.97-degree corner, limit 10 beveled the join and limit 15 let the 37-unit spike through.
- Dashes with square caps grew from 4 to 6 pixels, leaving 2-pixel gaps; phase 2 started halfway into the first dash.
- The cyclic
GradientPaintand theREFLECTcycle produce the same strip;REPEATjumps from white back to black. - The texture's checkerboard is stretched to 2 by 1 pixel cells and stays aligned to the anchor, not to the ellipse.
- The view transform maps the mouse at (60, 70) back to user point (5, 10): (60 - 40) / 4 and (70 - 30) / 4.
- The clip removed the diagonals left of x = 4 and outside the ellipse; the bottom line, drawn after
setClip(null), spans the whole image. - On the ARGB image, the destination-only pixel stays red under every rule, because the source was not drawn there. The source-only pixel ends up transparent under every rule with Fs = 0 or Fs = αd there:
CLEAR,DST,SRC_IN,DST_IN,DST_OUTandSRC_ATOP.
Common questions
Why does my rotation spin around the wrong point?
rotate(angle) turns around the origin of the current coordinate system. Use rotate(angle, cx, cy), or translate to the center, rotate, and translate back. Remember that the transform called last applies first.
How do I undo transforms or clips after drawing?
Work on a copy: Graphics2D g2 = (Graphics2D) g.create(); try { ... } finally { g2.dispose(); }. Alternatively save getTransform() and getClip() first and restore them, but the copy is simpler and safer.
How do I draw a semi-transparent shape?
Use a color with alpha (new Color(0, 0, 255, 100)), or set AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f) to make everything drawn afterwards 40% opaque.
How do I draw dashed lines that look the same at every zoom level? Dash lengths are in user units and scale with the transform. To keep them constant on screen, divide the pattern and the width by the current scale factor, or draw the line in device space after transforming its points yourself.
What's the difference between setClip and clip?
setClip replaces the clip, possibly enlarging it beyond the area Swing allowed. clip intersects with the existing clip, which is what you want inside paintComponent.
API reference
| Class / method | Purpose |
|---|---|
Graphics2D.setStroke, getStroke; Stroke.createStrokedShape | The pen used by draw. |
BasicStroke(width), (width, cap, join), (width, cap, join, miterLimit), (width, cap, join, miterLimit, dash, dashPhase) | Stroke attributes. |
CAP_BUTT, CAP_ROUND, CAP_SQUARE, JOIN_MITER, JOIN_ROUND, JOIN_BEVEL | Cap and join styles. |
Graphics2D.setPaint, getPaint; Color(r, g, b, a) | The paint used to fill. |
GradientPaint(p1, c1, p2, c2), GradientPaint(p1, c1, p2, c2, cyclic) | Two-color gradient. |
LinearGradientPaint(start, end, fractions, colors, cycle), RadialGradientPaint(center, radius, focus, fractions, colors, cycle), CycleMethod.NO_CYCLE/REFLECT/REPEAT | Multi-stop gradients (Java 6). |
TexturePaint(BufferedImage, Rectangle2D anchor) | Tiling with an image. |
Graphics2D.translate, rotate(angle), rotate(angle, x, y), scale, shear, transform(at), getTransform, setTransform | Transforming the context. |
AffineTransform(m00, m10, m01, m11, m02, m12), getRotateInstance, getScaleInstance, getTranslateInstance, getShearInstance, setToRotation, quadrantRotate | Creating transforms. |
concatenate, preConcatenate, transform, deltaTransform, inverseTransform, createInverse, createTransformedShape, getMatrix, getType | Using transforms. |
Graphics2D.clip(shape), Graphics.setClip, getClip, getClipBounds, hitClip | Clipping. |
TextLayout(text, font, frc), getOutline(at), getAdvance, getAscent, getDescent, getLeading, getBounds; Graphics2D.getFontRenderContext | Text outlines. |
Graphics2D.setComposite; AlphaComposite.getInstance(rule), getInstance(rule, alpha), derive, SrcOver | Composition. |
CLEAR, SRC, DST, SRC_OVER, DST_OVER, SRC_IN, DST_IN, SRC_OUT, DST_OUT, SRC_ATOP, DST_ATOP, XOR | Porter-Duff rules. |
Summary
- A
BasicStrokesets width, end caps, joins, the miter limit and a dash pattern with phase. Caps apply to every dash; the miter limit turns spikes at sharp corners into bevels. - Paints compute the fill color per pixel:
Color,GradientPaint, multi-stopLinearGradientPaintandRadialGradientPaintwith cycle methods, andTexturePaint. Gradients and textures are anchored in user space. - Affine transforms (scale, rotate, translate, shear) compose; the last one specified is applied first. Use
transformor the convenience methods, save and restore withgetTransform/setTransform, and never overwrite the existing transform, which can contain HiDPI or printer scaling.inverseTransformmaps mouse positions back to user space. clipintersects the clip with a shape, including text outlines fromTextLayout; avoid replacing the clip withsetClip.AlphaCompositeblends source and destination with the Porter-Duff rules;SRC_OVERwith an extra alpha covers most needs, theIN/OUTrules make masks. Rules that use destination alpha need an ARGB image as the destination.
Practice Questions
1. A dashed line uses the pattern {5, 5} with CAP_ROUND and a width of 4. The gaps look much shorter than the dashes. Why?
End caps are applied to each dash. A round cap adds half the width, 2 units, at both ends of every dash, so each dash is 9 units long and each gap only 1 unit. Use CAP_BUTT for exact dash and gap lengths, or lengthen the gaps in the pattern by the stroke width.
2. Code calls g2.translate(cx, cy) and then g2.rotate(angle) before drawing a clock hand defined around the origin. Does the hand rotate around the origin or around (cx, cy)?
Around (cx, cy), and that is the intended effect. The last specified transformation is applied first: the hand is rotated around the origin, where it was defined, and then translated so that the origin lands at (cx, cy). Specifying the two calls in the other order would rotate the already translated hand around the origin of the component, swinging it across the screen.
3. Why is g2.setTransform(myTransform) in paintComponent a bug, even if the program looks right on the developer's machine?
It replaces the context's existing transform instead of composing with it. On a HiDPI display, Swing's context already contains a scale of, say, 2, and when printing the context contains the page rotation and the scale to printer resolution. Replacing it draws at the wrong size or position on such devices. Use g2.transform(myTransform) (or translate, rotate and so on), and use setTransform only to restore a transform saved with getTransform.
4. A program draws a round profile picture by calling clip(new Ellipse2D.Double(...)) and then drawImage. The edge of the circle is jagged even with antialiasing on. How can it be smoothed?
Clipping is pixel based: a pixel is either inside or outside the clip, and the antialiasing hint does not soften clip edges. Instead, create a TYPE_INT_ARGB image, fill the circle into it with antialiasing on (soft edge pixels get partial alpha), set AlphaComposite.SrcIn, and draw the photo into that image. The photo keeps only the parts covered by the circle, weighted by the circle's alpha. Then draw the result onto the screen.
5. Under DST_IN, what happens to the destination where a source with alpha 0.3 is drawn, and why does the source color not matter?
DST_IN has the factors Fs = 0 and Fd = αs. The source color is multiplied by 0 and so never appears; the destination is multiplied by the source alpha 0.3, so it keeps 30% of its opacity there (and premultiplied color). It is a way to apply a mask's alpha to an existing picture. Where no source is drawn, the destination is unaffected. On a destination without an alpha channel, the reduced alpha cannot be stored: in a TYPE_INT_RGB image the JDK leaves such a pixel completely unchanged.
Previous: Java 2D Rendering Pipeline: Shapes, Paths and Constructive Area Geometry
Next: Raster Images in Java: ImageIO, BufferedImage Pixels and Image Filters
Related reading
- Java 2D Rendering Pipeline: Shapes, Paths and Constructive Area Geometry
- Swing Trees: JTree, Tree Models, Nodes and Paths
- Swing Table Cell Renderers and Editors: Custom Rendering and Editing
- Swing Tables: JTable, Table Models, Sorting and Filtering
- Swing Dialogs: JOptionPane, Custom Dialogs and JFileChooser

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.