12 Java 2D PDF
12 Java 2D PDF
2D Drawing
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Agenda
Overview
Drawing Shapes
Paint Styles
Transparency
Using Local Fonts
Stroke Styles
Coordinate
Transformations
Requesting
Drawing Accuracy
4
AWT
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
g2d.draw(s);
g2d.fill(s);
5
// outline
// solid
Note
All methods that return Graphics in Java return
Graphics2D in Java 2 and later
paint, paintComponent
getGraphics
6
g2d.setPaint(fillColorOrPattern);
g2d.setStroke(penThicknessOrPattern);
g2d.setComposite(someAlphaComposite);
g2d.setFont(someFont);
g2d.translate(...);
g2d.rotate(...);
g2d.scale(...);
g2d.shear(...);
g2d.setTransform(someAffineTransform);
Note
Most shapes are in the java.awt.geom package
There is a corresponding Shape class for most of the
drawXxx methods of Graphics (see next slide)
8
Arc2D.Double, Arc2D.Float
Area (a shape built by union, intersection, subtraction and xor of
other shapes)
CubicCurve2D.Double, CubicCurve2D.Float
Ellipse2D.Double, Ellipse2D.Float
GeneralPath (a series of connected shapes), Polygon
Line2D.Double, Line2D.Float
QuadCurve2D.Double, QuadCurve2D.Float (a spline curve)
Rectangle2D.Double, Rectangle2D.Float, Rectangle
RoundRectangle2D.Double, RoundRectangle2D.Float
10
12
13
GradientPaint
Constructors take two points, two colors, and optionally a
boolean flag that indicates that the color pattern should
cycle. Colors fade from one color to the other.
TexturePaint
Constructor takes a BufferedImage and a Rectangle2D,
maps the image to the rectangle, then tiles the rectangle.
14
15
16
A Rectangle2D
Specifies where tiling starts
18
Custom BufferedImage:
Example Code
int width = 32;
int height = 32;
BufferedImage bufferedImage =
new BufferedImage(width, height
BufferedImage.TYPE_INT_RGB);
Graphics2D g2dImg = bufferedImage.createGraphics();
g2dImg.draw(...); // Draws onto image
g2dImg.fill(...); // Draws onto image
TexturePaint texture =
new TexturePaint(bufferedImage,
new Rectangle(0, 0, width, height));
g2d.setPaint(texture);
g2d.draw(...); // Draws onto window
g2d.fill(...); // Draws onto window
19
javax.swing.*;
java.awt.*;
java.awt.geom.*;
java.awt.image.*;
23
24
25
Normal steps
Create an AlphaComposite object
Call AlphaComposite.getInstance with a mixing rule
designator and a transparency (or "alpha") value.
There are 12 built-in mixing rules (see the
AlphaComposite API for details), but you only care about
AlphaComposite.SRC_OVER.
Alpha values range from 0.0F (completely transparent) to
1.0F (completely opaque).
26
Transparent Drawing:
Example Code
public class TransparencyExample extends JPanel {
...
private AlphaComposite makeComposite(float alpha) {
int type = AlphaComposite.SRC_OVER;
return(AlphaComposite.getInstance(type, alpha));
}
27
Transparent Drawing:
Example Code (Continued)
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
for(int i=0; i<11; i++) {
drawSquares(g2d, i*0.1F); // 2nd arg is transparency
g2d.translate(deltaX, 0);
}
28
29
Then
env.getAvailableFontFamilyNames();
or
env.getAllFonts();
// Much slower than just getting names!
Safest Option:
Supply list of preferred font names in order, loop down
looking for first match. Supply standard font name as
backup.
30
31
Example 2:
Drawing with Local Fonts
public class FontExample extends GradientPaintExample {
public FontExample() {
GraphicsEnvironment env =
GraphicsEnvironment.getLocalGraphicsEnvironment();
env.getAvailableFontFamilyNames();
setFont(new Font("Goudy Handtooled BT", Font.PLAIN, 100));
}
protected void drawBigString(Graphics2D g2d) {
g2d.setPaint(Color.BLACK);
g2d.drawString("Java 2D", 25, 215);
}
public void paintComponent(Graphics g) {
clear(g);
Graphics2D g2d = (Graphics2D)g;
drawGradientCircle(g2d);
drawBigString(g2d);
} ...
32
33
Java2D
Pen thickness
Dashing pattern
Line join/cap styles
Setting styles
34
Stroke Attributes
Normal use: Use setStroke to assign a
BasicStroke. BasicStroke constructors:
BasicStroke()
Creates a BasicStroke with a pen width of 1.0, the default cap style of
CAP_SQUARE, and the default join style of JOIN_MITER.
BasicStroke(float penWidth)
Uses the specified pen width and the default cap/join styles.
35
37
38
39
Join Styles
JOIN_MITER
Extend outside edges of lines until they meet
This is the default
JOIN_BEVEL
Connect outside corners of outlines with straight line
JOIN_ROUND
Round off corner with a circle that has diameter equal to
the pen width
40
Cap Styles
CAP_SQUARE
Make a square cap that extends past the end point by half
the pen width
This is the default
CAP_BUTT
Cut off segment exactly at end point
Use this one for dashed lines.
CAP_ROUND
Make a circle centered on the end point. Use a diameter
equal to the pen width.
41
42
43
Coordinate Transformations
Idea:
Instead of computing new coordinates, move the
coordinate system itself.
Available Transformations
Translate (move).
Rotate (spin).
Scale (stretch evenly)
Shear (stretch more as points get further from origin)
Custom. New point (x2, y2) derived from original point
(x1, y1) as follows:
[ x2]
[
[ y2] = [
[ 1 ]
[
44
m00
m10
0
m01
m11
0
m02
m12
1
] [ x1 ]
[ m00x1 + m01y1 + m02 ]
] [ y1 ] = [ m10x1 + m11y1 + m12 ]
] [ 1 ]
[
1
]
Java EE training: http://courses.coreservlets.com
45
46
Shear Transformations
Meaning of Shear
X Shear
If you specify a non-zero x shear, then x values will be
more and more shifted to the right the farther they are
away from the y axis. For example, an x shear of 0.1
means that the x value will be shifted 10% of the distance
the point is away from the y axis.
Y Shear
Points are shifted down in proportion to the distance they
are away from the x axis.
47
48
49
Rendering Hints
Default:
Faster drawing, possibly less accuracy
Rendering Hints:
Let you request more accurate (but generally slower)
drawing. Eg:
50
RenderingHints renderHints =
new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
renderHints.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
...
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.addRenderingHints(renderHints);
...
Java EE training: http://courses.coreservlets.com
Summary
General
If you have Graphics, cast it to Graphics2D
Create Shape objects, then call Graphics2Ds draw and
fill methods with shapes as args.
Paint styles
Use setPaint to specify a solid color (Color), a gradient
fill (GradientPaint), or tiled image (TexturePaint).
TexturePaint requires a BufferedImage, which you can
create from an image file by creating empty
BufferedImage then drawing image into it.
Transparent drawing
51
Summary (Continued)
Local fonts
Look up locally installed fonts with
getAvailableFontFamilyNames. Then supply name to
Font constructor and specify font via setFont.
Stroke styles
BasicStroke lets you set pen thickness, dashing pattern,
and line cap/join styles. Then call setStroke.
Coordinate transformations
Let you move the coordinate system rather than changing
what you draw. Simple transforms: call translate, rotate,
scale, and shear. More complex transforms: supply matrix
to AffineTransform constructor, then call setTransform.
Rendering Hints
52
Questions?
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
Developed and taught by well-known author and developer. At public venues or onsite at your location.