Java Drawing in 2D
Trịnh Thị Vân Anh
Contents
Drawing Shapes
Paint Styles
Transparency
Using Local Fonts
Stroke Styles
Coordinate Transformations
Working with Images
Drawing Shapes
AWT
1. public void paint(Graphics g){
2. [Link](g);
3. [Link]([Link]);
4. [Link](20, 20, 100, 100);
5. [Link](130, 100, 100, 100);
6. }
Java 2D
1. public void paintComponent(Graphics g2){
2. [Link](g2);
3. Graphics2D g=(Graphics2D)g2;
4. [Link]([Link]);
5. [Link]([Link]);
6. [Link](new BasicStroke(7));
7. [Link](10,10,100,100);
8. }
Drawing methods based on
values
1. void drawLine(int x1, int y1, int x2, int y2)
2. void drawOval(int x, int y, int width, int height)
3. void drawPolygon(int[] xPoints, int[] yPoints, int
nPoints)
4. void drawPolygon(Polygon p)
5. void drawPolyline(int[] xPoints, int[] yPoints, int
nPoints)
6. void drawRect(int x, int y, int width, int height)
7. void drawRoundRect(int x,int y,int width,int
height,int arcWidth,int arcHeight)
Drawing methods based on
shape objects
a) void draw(Shape s)
b) void clip(Shape s)
c) void fill(Shape s)
d) void rotate(double theta)
e) void rotate(double theta, double x, double y)
f) void scale(double sx, double sy)
g) void shear(double shx, double shy)
h) void transform(AffineTransform Tx)
i) void translate(double tx, double ty)
j) void translate(int x, int y)
Java 2D Drawing Process:
Step 1
Cast Graphics object to Graphics2D
1. public void paintComponent(Graphics g) {
2. [Link](g); // Typical Swing
3. Graphics2D g2d = (Graphics2D)g;
4. [Link](...);
5. ...
6. }
Step 1
Note
All methods that return Graphics in Java return
Graphics2D in Java 2 and later
Paint(), paintComponent()
getGraphics()
Step 2
Set pen parameters
[Link](fillColorOrPattern);
[Link](penThicknessOrPattern);
[Link](someFont);
[Link](...);
[Link](...);
[Link](...);
[Link](...);
[Link](someAffineTransform);
Step 3
Create a Shape object.
[Link] rect = ...;
[Link] ellipse = ...;
Polygon poly = ...;
GeneralPath path = ...;
SomeShapeYouDefined shape = ...;
Note
Most shapes are in the [Link] package
There is a corresponding Shape class for most of
the drawXxxmethods of Graphics
Built-in Shape Classes
1. [Link], [Link]
2. Area (a shape built by union, intersection,
subtraction and xor of other shapes)
3. [Link], [Link]
4. [Link], [Link]
5. GeneralPath (a series of connected shapes), Polygon
6. [Link], [Link]
7. [Link], [Link] (a spline
curve)
8. [Link], [Link], Rectangle
9. [Link],
[Link]
Step 4
Draw an outlined or filled version of the Shape
[Link](someShape);
[Link](someShape);
The legacy methods are still supported
drawString still commonly used
drawLine, drawRect, fillRect still somewhat
used
Example Code
Drawing with Mouse
The following demonstration
will depict how to draw shapes
using mouse events.
Left,to width p2
A shape is determined by two p
points: p1 (when user presses
the mouse) and p2 (when user height
releases the mouse).
If an ellipse or a rectangle is p1
chosen, from p1 and p2, the
drawing area is determined
appropriately.
DrawWithMouse: Design
Output
repaint() –DrawSimple-design
Output
Paint Styles
Paint Styles
Idea
Use setPaint and getPaint to change and retrieve the
Paint settings.
Note that setPaint and getPaint supersede the setColor
and getColor methods that were used in Graphics (and
inherited in Graphics2D).
When you fill a Shape, the current Paint attribute of the
Graphics2D object is used.
Possible arguments to setPaint are:
A Color (solid color--Color implements Paint interface)
A GradientPaint (gradually-changing color
combination)
A TexturePaint (tiled image)
A new version of Paint that you write yourself.
Paint Classes
Color
Has the same constants ([Link], [Link],
etc.) as the AWT version, plus some extra constructors.
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.
Simple Colors
In paint
1. public void paint(Graphics g) {
2. Graphics2D g2d = (Graphics2D)g;
3. [Link]([Link]); …….
In paintComponent
1. public void paintComponent(Graphics g) {
2. Graphics2D g2d = (Graphics2D)g;
3. [Link]([Link]); ……
From event handler
1. public void mousePressed(MouseEvent e) {
2. Graphics g = getGraphics();
3. Graphics2D g2d = (Graphics2D)g;
4. [Link]([Link]); …………
TexturePaint (Tiled Images as Fill
Patterns)
Step 1
Create a TexturePaint object. TexturePaint
constructor takes:
A BufferedImage : Specifies what to draw
A Rectangle2D: Specifies where tiling starts
• Step 2
Use the setPaint method of Graphics2D to
specify that this TexturePaint object be used.
Creating a BufferedImage for
Custom Drawing
Call the BufferedImage constructor with
A width
A height
A value of BufferedImage.TYPE_INT_RGB,
Call createGraphics on the result to get a
Graphics2D that refers to image
Use that Graphics2D object to draw onto the
BufferedImage
Custom BufferedImage (Code)
1. int width = 32; int height = 32;
2. BufferedImage bufferedImage = new
BufferedImage(width, height
BufferedImage.TYPE_INT_RGB);
3. Graphics2D g2dImg = [Link]();
4. [Link](...); // Draws onto image
5. [Link](...); // Draws onto image
6. TexturePaint texture = new
TexturePaint(bufferedImage, new Rectangle(0, 0, width,
height));
7. [Link](texture);
8. [Link](...); // Draws onto window
9. [Link](...); // Draws onto window
Creating a BufferedImage from
an Image File
Quick summary
Load an Image from an image file via getImage
Use MediaTracker to be sure it is done loading
Create an empty BufferedImage using the Image width
and height
Get the Graphics2D via createGraphics
Draw the Image onto the BufferedImage
Utility class
This process has been wrapped up in the
getBufferedImage method of the ImageUtilities class
BufferedImage from Image File
(code)
Tiled Images as Fill Patterns
(code)
Output
House (code)
Transparent
Transparent: Overview
Idea
Assign transparency (alpha) values to drawing
operations so that the underlying graphics partially
shows through when you draw shapes or images.
Normal steps
Create an AlphaComposite object
Call [Link] 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).
Pass the AlphaComposite object to the
setCompositemethod of the Graphics2D
Transparent Drawing (code)
Output
Using Local Fonts
Fonts
Local fonts: look up fonts first
Use the getAvailableFontFamilyNames or getAllFonts
methods of GraphicsEnvironment. E.g.:
GraphicsEnvironment env =
[Link]();
Then [Link]();
or [Link]();
// 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.
Example 1: Local Font Names
Example 2
Output
MainAllFont
Get system fonts
Create a font object
Assign a font object to graphics object
Draw text on a component
Get font metrics
Design
Output
Stroke Styles
Stroke Styles: Overview
AWT
drawXxxmethods of Graphics resulted in solid, 1-pixel
wide lines.
Predefined line join/cap styles for drawRect,
drawPolygon, etc.
Java2D
Pen thickness
Dashing pattern
Line join/cap styles
Setting styles
Create a BasicStroke object
Use the setStroke method to tell the Graphics2D object
to use it
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.
BasicStroke(float penWidth, int capStyle, int joinStyle)
Uses the specified pen width, cap style, and join style.
BasicStroke(float penWidth, int capStyle, int joinStyle, float
miterLimit)
Limits how far up the miter join can go (default is 10.0). Stay
away from this.
Thick Lines (code)
Output
Dashed Lines (code)
Output
Transformations
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:
Translations and Rotations (code)
1. public class RotateDemo extends StrokeThickness{
2. private Color[] colors = { [Link], [Link] };
3. public void paintComponent(Graphics g) {
4. [Link](g);
5. Graphics2D g2d = (Graphics2D)g;
6. drawGradientCircle(g2d);
7. drawThickCircleOutline(g2d);
8. [Link](234.0, 234.0);
9. for (int i=0; i<8; i++) {
10. [Link]([Link]/4.0);
11. [Link](colors[i%2]);
12. [Link]("Java", 0, 0);
13. } }
Scaling
Scaling is done with the scale() method. In this
method, we provide two parameters. They are the x
scale and y scale factor, by which coordinates are
scaled along the x or y axis respectively.
1. public class Scaling extends [Link] {
2. private void doDrawing(Graphics g) {
3. Graphics2D g2d = (Graphics2D) [Link]();
4. [Link](new Color(150, 150, 150));
5. [Link](20, 20, 80, 50);
6. AffineTransform tx1 = new AffineTransform();
7. [Link](110, 22);
1. [Link](0.5, 0.5);
2. [Link](tx1);
3. [Link](0, 0, 80, 50);
4. AffineTransform tx2 = new AffineTransform();
5. [Link](170, 20);
6. [Link](2.0, 1.5);
7. [Link](tx2);
8. [Link](0, 0, 80, 50);
9. [Link]();
10. }
11. public void paintComponent(Graphics g) {
12. [Link](g);
13. doDrawing(g);}
Output
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 go in the y direction. 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 x axis.
Y shear
Points are shifted down in proportion to the
distance they are to the right (x direction) from
the y axis.
Shear (code)
1. public class ShearDemo extends [Link] {
2. private static int gap=10, width=100;
3. private Rectangle rect = new Rectangle(gap, gap, 100, 100);
4. public void paintComponent(Graphics g) {
5. [Link](g);
6. Graphics2D g2d = (Graphics2D)g;
7. for (int i=0; i<5; i++) {
8. [Link]([Link]);
9. [Link](rect);
10. [Link](0.2, 0.0);
11. [Link](2*gap + width, 0);
12. } }
Shearing – AffineTransform (code)
1. public class Shearing extends [Link] {
2. private void doDrawing(Graphics g) {
3. Graphics2D g2d = (Graphics2D) [Link]();
4. AffineTransform tx1 = new AffineTransform();
5. [Link](50, 90); [Link](tx1);
6. [Link]([Link]);
7. [Link](0, 0, 160, 50);
8. AffineTransform tx2 = new AffineTransform();
9. [Link](50, 90); [Link](0, 1);
10. [Link](tx2); [Link]([Link]);
11. [Link](new Rectangle(0, 0, 80, 50));
1. AffineTransform tx3 = new AffineTransform();
2. [Link](130, 10);
3. [Link](0, 1);
4. [Link](tx3);
5. [Link]([Link]);
6. [Link](0, 0, 80, 50);
7. [Link]();
8. }
9. @Override
10. public void paintComponent(Graphics g) {
11. [Link](g);
12. doDrawing(g);
13. }}
Working with Images
Reading/Loading an Image
Loading a local image: Package
BufferedImage img = null; [Link]
try { contains methods for reading/writing
image files
img = [Link](new
File("[Link]"));
} catch (IOException e) { }
Loading a remote image: The method getCodeBase() will
try { create a connection to server to get
the resource
URL url = new
URL(getCodeBase(),"examples/[Link]
");
img = [Link](url);
} catch (IOException e) { }
Drawing an Image
Use the method drawImage(…) of the Graphics class
boolean [Link](image, x, y,…);
x, y: left corner of the drawing area
PhotoViewer : Design
View Image
1. private void
jButton3ActionPerformed([Link]
nt evt) {
2. String url=[Link]();
3. try{
4. img=[Link](new File(url));
5. }catch(Exception e){
6. }
7. [Link](img, 20,30,400,300, this);
8. }
Output