Java 2 D
Java 2 D
Provides
Rendering process
Graphics2D
Graphics
Primitives
Shapes
Text
Images
Transformation
fill()
stroke
draw()
font
DrawString()
drawImage()
Rendering hints
rasterizer
Clipping shape
paint
images
Compositing rule
Output
Devices
2D Graphics
The Java 2D API enables you to control
Line Thickness
Fills
Move, rotate, scale, and shear text and graphics
Composites
The Java 2D APIs are closely integrated with the Abstract Windowing
Toolkit (AWT).
Coordinate Spaces
Java 2D objects live in User Space, defined by Cartesian coordinates
Objects rendered to an output device are transformed into Device
Space for that device.
Usually one unit of device space corresponds to one pixel on the device.
The Rasterizer
Inside the rendering pipeline, the rasterizer takes ideal shapes within
your program and produces coverage values for each pixel on a
display device.
The coverage values represent how much of each pixel is covered by
the shape.
These coverage values are called alpha values.
The alpha value indicates the transparency of the color itself.
Alpha values range from 0.0 to 1.0, 0.0 being fully transparent, 1.0
being fully opaque.
Anti-aliased shapes often have pixels with non 0.0/1.0 values at their
edges
Drawing Shapes
Except for Point2D and Dimension2D, each of the geometry classes
implements the Shape interface.
With these classes you can create virtually any geometric shape and
render it through Graphics2D by calling the draw method or the fill
method.
To draw someShape
g2d.draw(someShape);
g2d.fill(someShape);
Painting in Java
In AWT, painting was done in the paint(Graphics g) method of a
java.awt.Canvas
In Swing, you will do painting in the paintComponent(Graphics g)
method of a javax.swing.JComponent
JComponents paint() method now calls paintComponent(),
paintBorder() and paintChildren()
Changes to the Graphics2D object within paint stay within the
paintComponent() method.
With the exception of Rendering Hints
SimpleShapes.java
Colors in Java 2
SystemColors
JFC allows you to set colors relative to desktop
Use UIManager.getColor(String itemName) to pull the current look and
feel colors into your application
For Example, if you wanted to set the background of your window to
the default background on the look and feel you are using, you would
use
setBackground(UIManager.getColor(window))
Color keys
Point2D
Arc2D
Area
CubicCurve2D
Dimension2D
Ellipse2D
GeneralPath
Points
A point is not a pixel
Point2D is an abstract class
Contains inner children
Point2d.Float and Point2D.Double
Point is still left over from AWT 1.0, holds coordinates as integers
Point2D includes methods for calculating the distance between two
points
public double distance (double PX, double PY)
public double distance (Point2D pt)
Shapes
Common interface implemented by several classes with 2D package
Four groups of methods in interface
getBounds()
contains
(x,y), Point2D, Rectangle2D
intersects()
(x,y,w,h) and Rectangle2D
getPathIterator()
move
line
quad
cubic
close
Winding Rules
If you fill an abstract shape, how does it get filled?
A winding rule determines what part of a shape is defined as the
interior, and consequently what part of the shape will be filled by a
call to fill()
Even-odd rule
Draw a line through the entire shape
Each time the line crosses the shapes border, increment a counter
When the counter is even, the line is outside the shape, odd is in
Non-zero (overlapping)
Draw a line through the entire shape
As line crosses each edge a +1 is counted for edges drawn from left to
right, -1 for right to left
Non zero regions are considered the interior of the shape
1 2
4
3
Even-odd
-1
0
-1 -2
Non-zero
GeneralPath
Allows you to build a path, segment by segment
public GeneralPath()
Uses non-zero as default winding rule
Common methods
moveTo(float x, float y)
lineTo(float x, float y)
quadTo(float controlX1, float controlY1, float endX, float endY)
cubicTo(float controlX1, float controlY1, float controlX2, float
controlY2, float endX, float endY)
append(Shape s, boolean connect)
closePath()
QuadCurve2D
doubles and Point2Ds as arguments
CubicCurve2D
doubles and Point2Ds as arguments
Rectangles
RectangularShape is an abstract class that is used in several children
Supplies some common methods
Rectangle2D
Double and Float versions
boolean intersectsLine() sees if a line intersects a Rectangle2D
public int outcode(Point2D)
masked integer which holds combination of OUT_TOP, OUT_BOTTOM,
OUT_LEFT and OUT_RIGHT
Ellipse2D
Ellipse specified by a rectangle
Arc2D
addition
intersection
subtraction
exclusive or
You create an Area, usually empty at first, and work from there
Area is just another implementation of the Shape interface
Original
Shapes
addition
intersection subtraction
Xor
Line Styles
Used when drawing an object
Line styles are defined by the stroke attribute in the Graphics2D
rendering context.
A BasicStroke object holds information about the line width, join
style, end-cap style, and dash style.
The line width is the thickness of the line measured perpendicular to its
trajectory. The line width is specified as a float value in user coordinate
units, which are roughly equivalent to 1/72 inch when the default
transform is used.
Dash Styles
The dash style defines the pattern of opaque and transparent sections
applied along the length of the line.
The dash style is defined by a dash array and a dash phase.
The dash array defines the dash pattern.
The dash phase is an offset into the dash pattern
Note that join styles and end caps apply to individual dashes in a dash
style
BasicStroke object
Constructors
public BasicStroke(float width,
int cap,
int join,
float miterlimit,
float[] dash,
float dash_phase)
public BasicStroke(float width,
int cap,
int join,
float miterlimit)
public BasicStroke(float width,
int cap,
int join)
public BasicStroke(float width)
public BasicStroke()
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).
Arguments to the Graphics2D setPaint method (and return values of getPaint) must
implement the Paint interface. Here are the major built-in Paint classes:
Color
GradientPaint
TexturePaint
Gradient Fills
Use GradientPaint class from java.awt package
The GradientPaint class provides a way to fill a Shape with a linear
color gradient pattern.
Given a starting point P1 with Color C1, and an ending point P2 with a
color C2
If the gradient is cyclic then the points on the extended P1, P2 connecting
line cycle back and forth between the colors C1 and C2.
If the gradient is acyclic then points on the P1 side of the segment have
the constant Color C1 while points on the P2 side have the constant Color
C2.
A Rectangle2D
Specifies how big the tiled image is
Note that the Rectangle2D object can be set to the image size, creating
an image tile the same size as the original image, or it could be set to a
different dimension
BufferedImage class
Once we have loaded an image, we need to place it into a
BufferedImage class
BufferedImage
The immediate-mode imaging model enables you to manipulate and
display pixel-mapped images whose data is stored in memory. You can
access image data in a variety of formats and use several types of filtering
operations to manipulate the data.
BufferedImage is the key class in the immediate-mode imaging API. This
class manages an image in memory and provides methods for storing,
interpreting, and rendering the pixel data. A BufferedImage can be
rendered through either a Graphics or a Graphics2D rendering context.
A BufferedImage is essentially an Image with an accessible data buffer. A
BufferedImage has a ColorModel and a Raster of image data.
image = getToolkit().getImage(imageFile);
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(image, 0);
try {
tracker.waitForAll();
} catch(InterruptedException ie) {}
if (tracker.isErrorAny()) return;
BufferedImage bufferedImage =
new BufferedImage(image.getWidth(this), image.getHeight(this),
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bufferedImage.createGraphics();
g2d.drawImage(image, 0, 0, this);
You still need to create the BufferedImage, but you dont need to
mess with the MediaTracker code for a single image.
Fonts
Cornerstone of 2D APIs text rendering system
Fonts can have three different names
Family name
Face name(Font name)
Garamond Italic is a font face name for a font whose family is Garamond
Logical names
Used before the 2D API to uniquely identify fonts.
Toolkits getFontList() returns a list of logical fonts
Deprecated method in JDK 1.2
Dialog
DialogInput
Serif
SansSerif
ZapfDingbats
Monospaced
Available Fonts
Of course there are a few idiosyncrasies
Logical fonts exist, and are mapped to local fonts using the font.properties
file in the jre/lib directory
There is a set of Physical Fonts, these are located in the jre/lib/fonts
subdirectory of the JDK installation. They are available on any platform
with Java2 installed. Each family has a Regular, Bold, Oblique and Bold
Oblique style
Local Fonts
First you need a GraphicsEnvironment instance that represents your
system.
GraphicsEnvironment.getLocalGraphicsEnvironment()
You can then get an array of every font installed in your system with
the public Font[] getAllFonts() method
This can take a lot of time. Some systems may have hundreds of fonts,
and when you call this method, you get to wait for a bit.
You can also get just the names of Fonts, (not the Fonts themselves)
with the public String[] getAvailableFontFamilyNames()
method instead, which is much faster.
FontRenderContextClass
When the rendering engine renders text, the results depend on the engines
transform and rendering hints
KEY_ANTIALIASING
KKEY_FRACTIONAL_METRICS
LineMetrics Class
Provides, ascent, descent, leading, height values for fonts
Text
2D API offers several options for rendering Text
Styled text
You can render styled text using an AttributedString and its
corresponding AttributedCharacterIterator.
First Create an AttributedString
AttributedString aString = new AttributedString(Foo Bar Baz)
TextLayout
drawString() renders simple pieces of code
TextLayout class supports
Text metrics
Hit testing
Caret Support
Highlighting support
Paragraph Layout on Multiple lines
Font Outline
Bi-directional text
Caret support
Wont draw a Caret, but gives you the information you need to draw one
yourself
Highlighting
Helps you calculate shapes you need to draw a highlight
Transparency of objects
Java2D permits you to assign transparency (alpha) values to drawing
operations so that the underlying graphics partially shows through
when you draw shapes or images.
To Create an AlphaComposite object
Call AlphaComposite.getInstance with a mixing rule designator and a
transparency (or "alpha") value.
There are 8 built-in mixing rules (see the AlphaComposite API for
details), but the one normally used for drawing with transparency settings
is AlphaComposite.SRC_OVER.
Alpha values range from 0.0f (completely transparent) to 1.0f
(completely opaque).
Enlarges to...
Coordinate Transformations
AffineTransformations - parallel lines are still parallel after
transformation
Graphics2D has an internal transformation that it applies to any
graphics device
You can modify or set this transform with
public setTransform(AffineTransform at)
public transform(AffineTransform at)
AffineTransformations
Embodies a mathematical concept that allows points to be transformed
into other points.
Uses 3x3 matrices to manipulate images
Note that with matrix multiplication AxB != BxA
All Graphics2D objects have a default, identity transform. This
transform should be used to reset the Graphics2D object when you are
done with the transform.
This object is used to transform coordinates from the user space (0,0) at
top left of window, to coordinates in the device space
Devices may be screens, printers, etc.
Available Transformations
Translate (move)
Rotate (spin).
Scale (stretch evenly)
Shear (stretch more as points get further from origin -- see example)
Custom. New point (x2, y2) derived from original point (x1, y1) as
follows:
[ x2]
[
[ y2] = [
[ 1 ]
[
m00
m10
0
m01
m11
0
m02
m12
1
] [ x1 ]
[ m00x1 + m01y1 + m02 ]
] [ y1 ] = [ m10x1 + m11y1 + m12 ]
] [ 1 ]
[
1
]
Applying:
Types of Transforms
Translation
public void translate(double tx, double ty)
adds translation to an AffineTransform
Rotation
public void rotate(double thetaRadians)
public void rotate(double thetaRadians, double x, double y)
Rotate around (x,y) not origin
Scaling
Line thickness is scaled. If you dont want this to happen, dont modify
the Graphics2D object, modify the shapes themselves
If you pass negative values, you can switch the direction of the axis
public void scale(double sx, double xy)
getScaleInstance()
Transforming shapes
public Shape createTransformedShape(Shape pSrc)
Uses an existing AffineTransform and transforms a given Shape and
returns the result as another Shape
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.
Rendering Hints
Default:
Faster drawing
Rendering Hints:
Let you request more accurate (but generally slower) drawing.
Example (highest quality):
RenderingHints renderHints =
new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
...
public void paintComponent(Graphics g) {
// super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHints(renderHints);
Images
An Image is a two-dimensional array of colors. Each element is called
a pixel
java.awt.Image is effectively just a box for image data, you can read
from it, but not modify it.
You can load Images using a MediaTracker object, shown earlier
Original Graphics support in AWT supplied six methods to draw
images
One pair to draw at a given location
The second to draw scaled image
The third pair to draw into a clipped rectangle
Blurring
Sharpening
Edge Detecting
Posterizing
Inversion
Brightness
Color Conversions
Devices in Java2D
One goal of the 2D API is to make the rendering process the same,
regardless of the output device.
GraphicsEnvironment
Knows about fonts on your computer
Can access screen devices (GraphicsDevice class)
TYPE_RASTER_SCREEN
TYPE_PRINTER
TYPE_IMAGE_BUFFER
Default AffineTransforms
Printing
Tucked away in the java.awt.print package
Not to be confused with the AWT versions which are still included!
java.awt.PrintJob etc...
java.awt.print.Printable
Interface represents something that can be printed, contains a single method,
print()
Printing Sequence
First a PrinterJob is instantiated by calling the
PrinterJob.getPrinterJob() method
The item to be printed is then passed to the PrinterJobs setPrintable()
method
A Print dialog is then shown
If the user presses ok, the printDialog() method returns true, and the
print job is started by calling the PrinterJob print() method
Control is returned to the application once the entire printing job has
been sent to the underlying OS.
PageFormat class
PrinterJob class
NO_SUCH_PAGE is returned.
All pages will have same page setup
Pageable interface
specifies a way to associate a PageFormat and a Printable with
each page of a print job.
java.awt.print.Book implements this interface
Downloads
Get the presentation at http://webdev.apl.jhu.edu/~
rbe/java/Java_2D/all.zip