Вы находитесь на странице: 1из 86

Java 2D API

Provides
A uniform rendering model for display devices and printers
A wide range of geometric primitives
Mechanisms for performing hit detection on shapes, tet, and images
A compositing model
!nhanced color support that facilitates color management
"upport for printing comple documents
Most importantly it is the #uilding #loc$s to your own custom
components%
&endering process
"hapes
Images
'et
'ransformation
stro$e
font
&endering hints
rasteri(er
)lipping shape paint )ompositing rule
fill*+
draw*+
Draw"tring*+
drawImage*+
images
Graphics
Primitives
Output
Devices
,raphics2D
2D ,raphics
'he Java 2D API ena#les you to control
-ine 'hic$ness
.ills
Move, rotate, scale, and shear tet and graphics
)omposites
Allows for comple graphics *)harts, overlays, etc/+
'he Java 2D API also ena#les you to store and to manipulate image
data
0lur
"harpen
'he Java 2D APIs are closely integrated with the A#stract 1indowing
'ool$it *A1'+%
)oordinate "paces
Java 2D o#2ects live in User Space, defined #y )artesian coordinates
3#2ects rendered to an output device are transformed into Device
Space for that device%
4sually one unit of device space corresponds to one piel on the device%
Default transformations converts 52 piels to one inch *typical screen
resolution+
Default transformation has physical screen si(e e6ual physical print
si(e
'he &asteri(er
Inside the rendering pipeline, the rasteri(er ta$es ideal shapes within
your program and produces coverage values for each piel on a
display device%
'he coverage values represent how much of each piel is covered #y
the shape%
'hese coverage values are called alpha values.
'he alpha value indicates the transparency of the color itself%
Alpha values range from 7%7 to 8%7, 7%7 #eing fully transparent, 8%7
#eing fully opa6ue%
Anti9aliased shapes often have piels with non 7%7:8%7 values at their
edges
)ompositing is used to decide how to translate alpha values into color
information
)ompositing determines how the colors of a new graphics primitive
are com#ined with the eisting colors on a drawing surface%
Drawing "hapes
!cept for Point2D and Dimension2D, each of the geometry classes
implements the "hape interface%
1ith these classes you can create virtually any geometric shape and
render it through ,raphics2D #y calling the draw method or the fill
method%
'o draw someShape
g2d.draw(someShape);
g2d.fill(someShape+;
Painting in Java
In A1', painting was done in the paint*,raphics g+ method of a
2ava%awt%)anvas
In "wing, you will do painting in the paint)omponent*,raphics g+
method of a 2ava%swing%J)omponent
J)omponent<s paint*+ method now calls paint)omponent*+,
paint0order*+ and paint)hildren*+
)hanges to the ,raphics2D o#2ect within paint stay within the
paint)omponent*+ method%
1ith the eception of &endering =ints
1ith the A1', you generally drew a shape #y calling the drawXxx or
fillXxx methods of the ,raphics o#2ect% In Java2D, you generally
create a "hape o#2ect, then call either the draw or fill method of the
,raphics2D o#2ect, supplying the "hape o#2ect as an argument% >ou<ll
still want draw"tring and drawImage, however% =ere<s an eample of
the normal approach?
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d (Graphics2D)g;
!! "ssume #$ %$ and diameter are instance variables
&llipse2D.Double circle
new &llipse2D.double(#$ %$ diameter$ diameter);
g2d.fill(circle);
...
'
Drawing "hapes? 3verview
"imple"hapes%2ava
Note rough edge to drawing
)olors in Java 2
)olor is found in 2ava%awt pac$age
Primarily unchanged through different A1':"wing versions
It is a class to encapsulate colors in the default s&,0 color space
Multiple )onstructors
)olor*float r, float g, float #,+
)olor*float r, float g, float #, float a+
)olor*int rg#+
&ed in #its 8@92A
,reen in #its B98C
0lue in #its 795
)olor*int r, int g, int #+
)olor*int r, int g, int #, int a+
"ystem)olors
J.) allows you to set colors relative to des$top
4se 4IManager%get)olor*"tring itemDame+ to pull the current loo$ and
feel colors into your application
.or !ample, if you wanted to set the #ac$ground of your window to
the default #ac$ground on the loo$ and feel you are using, you would
use
set0ac$ground*4IManager%get)olor*EwindowF++
4se these instead of the eplicit )olor o#2ects whenever possi#le
"ample values can #e found in Metal-oo$And.eel%2ava, #ut they wor$
in any of the -oo$ and .eels
)olor $eys
Gdes$topF 9 )olor of the des$top #ac$ground
Gactive)aptionG 9 )olor for captions *title #ars+ when they are active%
Gactive)aption'etG 9 'et color for tet in captions *title #ars+%
Gactive)aption0orderG 9 0order color for caption *title #ar+ window
#orders%
Ginactive)aptionG 9 )olor for captions *title #ars+ when not active%
Ginactive)aption'etG 9 'et color for tet in inactive captions *title
#ars+%
Ginactive)aption0orderG 9 0order color for inactive caption *title #ar+
window #orders%
GwindowF 9 Default color for the interior of windows
Gwindow0orderF 9 0order of window
Gwindow'etF 9 'et color of window
GmenuF 9 0ac$ground color for menus
Gmenu'etF 9 'et color for menus
More )olor $eys
GtetF 9 'et #ac$ground color
Gtet'etF 9 'et foreground color
Gtet=ighlightF 9 'et #ac$ground color when selected
Gtet=ighlight'etF 9 'et color when selected
GtetInactive'etF 9 'et color when disa#led
GcontrolF 9 Default color for controls *#uttons, sliders, etc+
Gcontrol'etF 9 Default color for tet in controls
Econtrol=ighlightF 9 "pecular highlight *opposite of the shadow+
Gcontrol-t=ighlightF 9 =ighlight color for controls
Gcontrol"hadowF 9 "hadow color for controls
GcontrolD$"hadowF 9 Dar$ shadow color for controls
Gscroll#arF 9 "croll#ar #ac$ground *usually the Gtrac$G+
GinfoF 9 'ool'ip 0ac$ground
Ginfo'etF 9 'ool'ip 'et
)lasses in the 2ava%awt%geom pac$age
Point2D
Arc2D
Area
)u#ic)urve2D
Dimension2D
!llipse2D
,eneralPath
Points
A point is not a piel
Point2D is an a#stract class
)ontains inner children
Point2d%.loat and Point2D%Dou#le
Point is still left over from A1' 8%7, holds coordinates as integers

Point2D includes methods for calculating the distance #etween two


points
pu#lic dou#le distance *dou#le PH, dou#le P>+
pu#lic dou#le distance *Point2D pt+
1hy floats and dou#lesI
"hapes
)ommon interface implemented #y several classes with 2D pac$age
.our groups of methods in interface
get0ounds*+
contains
*,y+, Point2D, &ectangle2D
intersects*+
*,y,w,h+ and &ectangle2D
getPathIterator*+
!ach "hape has a set of segments
move
line
6uad
cu#ic
close
1inding &ules
If you fill an a#stract shape, how does it get filledI
A winding rule determines what part of a shape is defined as the
interior, and conse6uently what part of the shape will #e filled #y a
call to fill*+
!ven9odd rule
Draw a line through the entire shape
!ach time the line crosses the shape<s #order, increment a counter
1hen the counter is even, the line is outside the shape, odd is in
Don9(ero *overlapping+
Draw a line through the entire shape
As line crosses each edge a J8 is counted for edges drawn from left to
right, 98 for right to left
Don (ero regions are considered the interior of the shape
98
1inding &ules Illustrated
8
92
5
@
C
K
A
2
8
7
7
7
98
!ven9odd Don9(ero
,eneralPath
Allows you to #uild a path, segment #y segment
pu#lic ,eneralPath*+
4ses non9(ero as default winding rule
pu#lic ,eneralPath*int winding&ule+
pu#lic ,eneralPath*int winding&ule, int Initial)apacity+
4se initial capacity if you are worried a#out performance
)ommon methods
move'o*float , float y+
line'o*float , float y+
6uad'o*float controlH8, float control>8, float endH, float end>+
cu#ic'o*float controlH8, float control>8, float controlH2, float
control>2, float endH, float end>+
append*"hape s, #oolean connect+
closePath*+
-ines and )urves
-ine2D
-ines ta$e dou#les, floats, and Point2Ds as arguments
set-ine*-ine2D line+ sets the endpoint of the line to #e the same as the
given line
Luad)urve2D
dou#les and Point2Ds as arguments
)u#ic)urve2D
dou#les and Point2Ds as arguments
&ectangles
&ectangular"hape is an a#stract class that is used in several children
"upplies some common methods
getH, get>, get1idth, get=eight, getMaH/%
get)enterH, get)enter>
set.rame*+ sets the #ounds of a rectangle using , y, w, and h
set.rame.romDiagonal*+ also sets the #ounds using two points
&ectangle2D
Dou#le and .loat versions
#oolean intersects-ine*+ sees if a line intersects a &ectangle2D
pu#lic int outcode*Point2D+
mas$ed integer which holds com#ination of 34'M'3P, 34'M03''3M,
34'M-!.' and 34'M&I,='
'he &ectangle from A1' is still around, and is a su#class of
&ectangle2D
&ound &ectangles, !llipses and Arc
&ound&ectangle
>ou specify the width and the height of the arc in the constructor
!llipse2D
!llipse specified #y a rectangle
Arc2D
'hree closure options, 3P!D, PI!, and )=3&D
"pecified #y , y, w, h, angle"tart, angle!tent, closure
Also specified #y Point2D:Dimension2D and #y &ectangle2D
setArc0y)enter*dou#le , dou#le y, dou#le r, dou#le angle"tart, dou#le
angle!tent+
)onstructive Area ,eometry
Allows you to #uild comple shapes #y com#ining simple shapes
addition
intersection
su#traction
eclusive or
>ou create an Area, usually empty at first, and wor$ from there
Area is 2ust another implementation of the "hape interface
addition
(riginal
Shapes
intersection subtraction )or
-ine "tyles
4sed when drawing an o#2ect
-ine styles are defined #y the stro$e attri#ute in the ,raphics2D
rendering contet%
A 0asic"tro$e o#2ect holds information a#out the line width, 2oin
style, end9cap style, and dash style%
'he line width is the thic$ness of the line measured perpendicular to its
tra2ectory% 'he line width is specified as a float value in user coordinate
units, which are roughly e6uivalent to 8:52 inch when the default
transform is used%
Join "tyles and !nd )aps
0asic"tro$e supports three 2oin styles?
J3IDM0!N!-
J3IDMMI'!&
J3IDM&34DD
'he end9cap style is the decoration that is applied where a line
segment ends% 0asic"tro$e supports three end9cap styles?
)APM04''
)APM&34DD
)APM"L4A&!
Dash "tyles
'he dash style defines the pattern of opa6ue and transparent sections
applied along the length of the line%
'he dash style is defined #y a dash array and a dash phase%
'he dash array defines the dash pattern%
'he dash phase is an offset into the dash pattern
Dote that 2oin styles and end caps apply to individual dashes in a dash
style
0asic"tro$e o#2ect
)onstructors
public *asicStro+e(float width$
int cap$
int ,oin$
float miterlimit$
float-. dash$
float dash/phase)
public *asicStro+e(float width$
int cap$
int ,oin$
float miterlimit)
public *asicStro+e(float width$
int cap$
int ,oin)
public *asicStro+e(float width)
public *asicStro+e()
)ode !ample, "imple"tro$e%2ava
.ill Patterns in Java2D?
3verview
1hen you fill a "hape, the current Paint attri#ute of the ,raphics2D o#2ect is used% 'his
can #e
a )olor *solid color+,
a ,radientPaint *gradient fill gradually com#ining two colors+,
a 'eturePaint *tiled image+, or
a new version of Paint that you write yourself%
4se setPaint and getPaint to change and retrieve the Paint settings%
Dote that setPaint and getPaint supersede the set)olor and get)olor methods that were
used in ,raphics *and inherited in ,raphics2D+%
Arguments to the ,raphics2D setPaint method *and return values of getPaint+ must
implement the Paint interface% =ere are the ma2or #uilt9in Paint classes?
)olor
,radientPaint
'eturePaint
,radient .ills
4se ,radientPaint class from 2ava%awt pac$age
'he ,radientPaint class provides a way to fill a "hape with a linear
color gradient pattern%
,iven a starting point P8 with )olor )8, and an ending point P2 with a
color )2
If the gradient is cyclic then the points on the etended P8, P2 connecting
line cycle #ac$ and forth #etween the colors )8 and )2%
If the gradient is acyclic then points on the P8 side of the segment have
the constant )olor )8 while points on the P2 side have the constant )olor
)2%
)ode !ample, ,radient!ample%2ava
)ode !ample, ,eneralPaths%2ava
)ode !ample, ,eneralPathsA%2ava
'iled Images as .ill Patterns
)reate a 'eturePaint 3#2ect% 'eturePaint )onstructor 'a$es?
A 0ufferedImage *see following pages+
"pecifies what to draw
A &ectangle2D
"pecifies how #ig the tiled image is
"pecify its use via the setPaint method of ,raphics2D
>ou can get a 0uffered Image in two #asic ways
4se ImageI3 class of JDO 8%K
0uild it with a ,I.
4se ImageI3 class of JDO 8%K
'he 2ava%imageio%ImageI3 class provides a set of static convenience
methods that perform most simple Image I:3 operations%

&eading an image that is in a standard format *,I., PD,, or JP!,+ is


simple?
0ile f new 0ile(1c23images3m%image.gif1);
*uffered4mage bi 4mage4(.read(f);
'he set of formats availa#le for reading can #e o#tained #y calling
ImageI3%get&eader.ormatDames%
'his will return an array of "trings containing the names of the availa#le
formats, such as GgifG and Gpng%G
1riting an image in a supported format is e6ually simple?
*uffered4mage bi;
0ile f new 0ile(1c23images3m%image.png1);
4mage4(.write(im$ 1png1$ f);
4sing the 0ufferedImage
3nce you have the 0ufferedImage, you then can use it as follows
!! image5ect is the area that the image will be mapped to
image5ect
new 5ectangle2D(6.6$ 6.6$ buffered4mage.get7idth()$
buffered4mage.get8eight());
image9aint:
new ;e#ture9aint(buffered4mage$ image5ect);
Dote that the &ectangle2D o#2ect can #e set to the image si(e, creating
an image tile the same si(e as the original image, or it could #e set to a
different dimension
)ode !ample, 'iledImages%2ava
3ld Method 8? 0uilding a 0uffered Image with a ,I.
.irst you need a Media 'rac$er to load the image
'he Media'rac$er class is a utility class to trac$ the status of a num#er
of media o#2ects% Media o#2ects could include audio clips as well as
images, though currently only images are supported
'o use a media trac$er, create an instance of Media'rac$er and call its
addImage method for each image to #e trac$ed% In addition, each
image can #e assigned a uni6ue identifier% 'his identifier controls the
priority order in which the images are fetched% It can also #e used to
identify uni6ue su#sets of the images that can #e waited on
independently% Images with a lower ID are loaded in preference to
those with a higher ID num#er%

4sing Media 'rac$ers
4sed to -oad an Image from an image file,
4se Media'rac$er to #e sure it is done loading,
4mage image c.get;ool+it().get4mage(image0ile);
<edia;rac+er trac+er new <edia;rac+er(c);
trac+er.add4mage(image$ 6);
tr% {
trac+er.wait0or"ll();
' catch(4nterrupted&#ception ie) {'
if (trac+er.is&rror"n%() return null);
Dote the use of pu#lic void wait.orAll*+
"tarts loading all images trac$ed #y this media trac$er% 'his method waits
until all the images #eing trac$ed have finished loading%
If there is an error while loading or scaling an image, then that image is
considered to have finished loading% 4se the is!rrorAny or is!rrorID
methods to chec$ for errors%
0ufferedImage class
3nce we have loaded an image, we need to place it into a
0ufferedImage class
0ufferedImage
'he immediate9mode imaging model ena#les you to manipulate and
display piel9mapped images whose data is stored in memory% >ou can
access image data in a variety of formats and use several types of filtering
operations to manipulate the data%
0ufferedImage is the $ey class in the immediate9mode imaging API% 'his
class manages an image in memory and provides methods for storing,
interpreting, and rendering the piel data% A 0ufferedImage can #e
rendered through either a ,raphics or a ,raphics2D rendering contet%
A 0ufferedImage is essentially an Image with an accessi#le data #uffer% A
0ufferedImage has a )olorModel and a &aster of image data%
'iling with 0uffered Images *,I.+
)reate an empty 0ufferedImage using the Image width and height,
,et the ,raphics2D via create,raphics,
Draw the Image onto the 0ufferedImage%
Image image get;ool+it().get4mage(image0ile);
<edia;rac+er trac+er new <edia;rac+er(this);
trac+er.add4mage(image$ 6);
tr% {
trac+er.wait0or"ll();
' catch(4nterrupted&#ception ie) {'
if (trac+er.is&rror"n%()) return;
*uffered4mage buffered4mage
new *uffered4mage(image.get7idth(this)$ image.get8eight(this)$
*uffered4mage.;=9&/4>;/5G*);
Graphics2D g2d buffered4mage.createGraphics();
g2d.draw4mage(image$ 6$ 6$ this);
3ld Method 2, 0uilding a 0ufferedImage using a ,I.
A <edia;rac+er starts a new thread, which loads images% 1hen
they are all loaded, the thread notifies the calling thread that it is done,
and the original thread continues
"wing offers the 4mage4con class, your one stop shop for creating
Images%
4mage image new 4mage4con(?du+e.gif@).get4mage()
>ou still need to create the *uffered4mage, #ut you don<t need to
mess with the <edia;rac+er code for a single image%
.onts
)ornerstone of 2D API<s tet rendering system
.onts can have three different names
.amily name
.ace name*.ont name+
Garamond Italic is a font face name for a font whose family is Garamond
-ogical names
4sed #efore the 2D API to uni6uely identify fonts%
'ool$it<s get0ontAist() returns a list of logical fonts
Deprecated method in JDO 8%2
,uaranteed to #e on every system
Mapped to local fonts on each system
Serif maps to ;imes >ew 5oman on 1inD'
P Dialog
P DialogInput
P "erif
P "ans"erif
P QapfDing#ats
P Monospaced
Availa#le .onts
3f course there are a few idiosyncrasies
-ogical fonts eist, and are mapped to local fonts using the font%properties
file in the 2re:li# directory
'here is a set of EPhysical .ontsF, these are located in the 2re:li#:fonts
su#directory of the JDO installation% 'hey are availa#le on any platform
with Java2 installed% !ach family has a &egular, 0old, 3#li6ue and 0old
3#li6ue style
-ucida "ans family
-ucida 0right family
-ucida "ans 'ypewriter family%
If only the J&! for Java2 is installed, only the -ucida "ans &egular font is
provided% *'his particularly applies to plug9in usage+
,etting access to local fonts is not o#vious
-ocal .onts
.irst you need a ,raphics!nvironment instance that represents your
system%
Graphics&nvironment.getAocalGraphics&nvironment()
>ou can then get an array of every font installed in your system with
the public 0ont-. get"ll0onts() method
'his can ta$e a lot of time% "ome systems may have hundreds of fonts,
and when you call this method, you get to wait for a #it%
>ou can also get 2ust the names of .onts, *not the .onts themselves+
with the public String-. get"vailable0ont0amil%>ames()
method instead, which is much faster%
!ample? -oading a -ocal .ont
-ets say you have a local font on your system called EAlladinF
"tep 8? ,et the local graphics environment
Graphics&nvironment ge
Graphics&nvironment.getAocalGraphics&nvironment();
"tep 2? If you want to use the 0ont.get0ont(?"lladin@) method,
you will need to call ge.get"ll0onts() first, or it will return null%
"tep 2 alternate? >ou could use the much faster
ge.get"vailable0ont0amil%>ames()
Printing 3ut All -ocal .ont Dames
!! 0rom 0onts.,ava
Graphics&nvironment en
Graphics&nvironment.getAocalGraphics&nvironment();
String-. font>ames
en.get"vailable0ont0amil%>ames();
S%stem.out.println(1"vailable 0onts21);
for(int i6; iBfont>ames.length; iCC)
S%stem.out.println(1 1 C font>ames-i.);
'
'
-oading Dynamic .onts
'he new method .ont%create.ont*int, Input"tream+ provides the a#ility to
add fonts to the Java 2 Nirtual Machine *JNM+ at runtime% 'his font is not
persistent upon termination of the JNM and is only availa#le to the creator
of the .ont%
At this time, only 'rue'ype'M fonts can #e created at runtime%
'he following code sample illustrates how to dynamically load the
'rue'ype font Arial from a file *Dynamic.ont%2ava+?
.ile file R new .ile*GArial%ttfG+;
.ileInput"tream fis R new .ileInput"tream*file+;
.ont font R .ont%create.ont*.ont%'&4!'>P!M.3D', fis+;
,etting Information on a .ont
.ontMetrics
In old A1', you would pass a .ont to the 'ool$it<s get0ont<etrics()
method
It has #een replaced with the ,ava.awt.font.Aine<etrics and
,ava.awt.font.0ont5enderConte#t classes
>ou can get a string #ounds from a font using its
getString*ounds(String$ 0ont5enderConte#t) method
>ou now as$ a 0ont for a Aine<etrics o#2ect #y calling one of its
getAine<etrics*+ methods
.ont&ender)ontet)lass
1hen the rendering engine renders tet, the results depend on the engine<s
transform and rendering hints
O!>MAD'IA-IA"ID,
OO!>M.&A)'I3DA-MM!'&I)"
>ou need to pass this information to the get-ineMetrics*+ method and
get"tring0ounds*+
More Information on a .ont
3ne you have a .ont&ender)ontet
>ou can get the the #ounds of a string with pu#lic &ectangle2D
get"tring0ounds*+%
'a$es "tring, charST, or )haracterIterator inde
.ont&ender)ontet
String title ?8ello 7orld@;
title0ont new 0ont(1Sans Serif1$ 0ont.9A"4>$ 2D);
font5enderConte#t new 0ont5enderConte#t(new "ffine;ransform()$
true$ false);
title0ont*ounds title0ont.getString*ounds(title$ font5enderConte#t);
-ineMetrics )lass
Provides, ascent, descent, leading, height/ values for fonts
'et
2D API offers several options for rendering 'et
4se a "wing component *J'et.ield, J'etArea, or J!ditorPane+%
Pass a character string to one of ,raphics2D<s draw"tring*+ methods
4se 'et-ayout
,lyph -evel manipulation

drawString(String str$ int #$ int %)

drawString(String str$ double #$ double %)


and y are the location of the string<s #aseline
Dote that fractional piel coordinates are not used #y renderer, they
are converted to ints
Allows caching of glyphs 9 performance and continuity enhancement, this
is also called grid fitting
"tyled tet
>ou can render styled tet using an "ttributedString and its
corresponding "ttributedCharacter4terator%
.irst )reate an Attri#uted"tring
"ttributedString aString new "ttributedString(?0oo *ar *aE@)
"econd, add attri#utes to the Attri#uted"tring%
4se the ,ava.awt.font.;e#t"ttribute class to get $ey values
'hird get the "ttributedCharacter4terator from the
"ttributedString
.ourth, pass the iterator to drawString()
drawString("ttributedCharacter4terator iterator$ int #$
int %)
>ou can even em#ed graphics within a St%ledString if you replace
characters with graphics%
)ode !ample, "tyled"tring%2ava
'et-ayout
draw"tring*+ renders simple pieces of code
'et-ayout class supports
'et metrics
=it testing
)aret "upport
=ighlighting support
Paragraph -ayout on Multiple lines
.ont 3utline
0i9directional tet
'et-ayout o#2ects use
'et
.ont
.ont&ender)ontet
'o &ender you use public void draw(Graphics 2D g2d$
float #$ float %)
'et -ayout features
=it 'esting
,iven a set of coordinates, you can get a 2ava%awt%font%'et=itInfo o#2ect
'his is a logical character inde, plus additional information *leading,
trailing+
)aret support
1on<t draw a )aret, #ut gives you the information you need to draw one
yourself
=ighlighting
=elps you calculate shapes you need to draw a highlight
)ode !ample, =ighlighting%2ava
'his is a good eample of other
features "wing gives you%
0oth show 'et-ayout and
=ighlighting
.irst uses .rame and paint*+ from
Java2D tet
"econd is modified to use J.rame
and paint)omponent*+
3nly when you run the code, do
you see the ma2or differences
'et-ayout and Multiline tet
If you use 2ava%awt%font%-ine0rea$Measurer, you can have 'et-ayout
dynamically lay out multiline tet

-ine0rea$Measurer uses an Attri#uted)haracterIterator and


.ont&ender)ontet to #rea$ up a string into individual lines
4ses pu#lic 'et-ayout net-ayout*+ method to parse the string into
individual 'et-ayout o#2ects
)ode !ample Paragraph-ayout%2ava
'o use 'et-ayout for .ont 3utlines
.irst, create one using a "tring, .ont, and .ont&ender)ontet
.ont&ender)ontet is used to get info on a &endered .ont
Det you need to get the outline of the font
"ffine;ransform te#t"t new "ffine;ransform();
te#t"t.translate(6$ (float)te#t;l.get*ounds().get8eight());
te#tShape te#t;l.get(utline(te#t"t);
'hen you can draw into the shape
)ode !ample, 'iledImages2%2ava
'ransparency of o#2ects
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%
'o )reate an Alpha)omposite o#2ect
)all Alpha)omposite%getInstance with a miing rule designator and a
transparency *or GalphaG+ value%
'here are B #uilt9in miing rules *see the Alpha)omposite API for
details+, #ut the one normally used for drawing with transparency settings
is Alpha)omposite%"&)M3N!&%
Alpha values range from 7%7f *completely transparent+ to 8%7f
*completely opa6ue+%
Alpha and )ompositing
&endering is an approimation%
1hen you as$ to have an ideal shape filled, the rendering engine
figures out how the piels of an output device should #e colored to
#est approimate the shape%
"peed vs% 6uality
.ast method *aliasing+
color the piels whose centers fall within the shape% 1ith this algorithm,
piels are either colored or not%
Luality method *anti9aliasing+
)alculate the intersection of the shape with each piel of the output
device%
Piels are colored in proportion to the amount they are covered #y the
shape%
)ode !ample, Alpha8%2ava
!nlarges to%%%
Don<t use anti9aliasing
for standard si(e screen
fonts% It will actually
reduce legi#ility%
"tandard screen fonts
have #een optimi(ed for
their si(e
)ode !ample, Alpha2%2ava
A -arger .ont !nlarges to%%%
)ode !ample, 'ransparency% 2ava
'wo ways of painting a
transparency
Ma$e a normal )olor o#2ect and then
call setPaint*+ and set)omposite*+
Ma$e a )olor o#2ect with &,0 and A
values, then 2ust call setPaint*+%
)olor*intr, intg, int#, inta+
)oordinate 'ransformations
Affine'ransformations 9 parallel lines are still parallel after
transformation
,raphics2D has an internal transformation that it applies to any
graphics device
>ou can modify or set this transform with
pu#lic set'ransform*Affine'ransform at+
pu#lic transform*Affine'ransform at+

>ou have two options when transforming things


'ransform the coordinate system
'ransform the shape
Affine'ransformations
!m#odies a mathematical concept that allows points to #e transformed
into other points%
4ses AA matrices to manipulate images
Dote that with matri multiplication A0 VR 0A
All ,raphics2D o#2ects have a default, identity transform% 'his
transform should #e used to reset the ,raphics2D o#2ect when you are
done with the transform%
'his o#2ect is used to transform coordinates from the user space *7,7+ at
top left of window, to coordinates in the device space
Devices may #e screens, printers, etc%
&emem#er that the ,raphics2D transform is applied to all rendering
operations and attri#utes% 'hat is the transform applies for drawing
and filling "hapes, drawing Images, and tet% Paint and "tro$e o#2ects
are also affected
'ransforming the )oordinate "ystem
Idea?
Instead of computing new coordinates, move the coordinate system itself%
Availa#le 'ransformations
'ranslate *move+
&otate *spin+%
"cale *stretch evenly+
"hear *stretch more as points get further from origin 99 see eample+
)ustom% Dew point *2, y2+ derived from original point *8, y8+ as
follows?
- #2. - m66 m6: m62 . - #: . - m66#: C m6:%: C m62 .
- %2. - m:6 m:: m:2 . - %: . - m:6#: C m::%: C m:2 .
- : . - 6 6 : . - : . - : .

Applying?
)all translate, rotate, scale, or shear on ,raphics2D o#2ect
)reate an Affine'ransform and apply it via set'ransform or transform

&emem#er, it is the coordinate system that is moving EunderneathF the o#2ect


you are printing
'ypes of 'ransforms
'ranslation
pu#lic void translate*dou#le t, dou#le ty+
adds translation to an Affine'ransform
pu#lic static Affine'ransform get'ranslateInstance*dou#le t, dou#le ty+
Ma$es a new Affine'ransform
&otation
pu#lic void rotate*dou#le theta&adians+
pu#lic void rotate*dou#le theta&adians, dou#le , dou#le y+
&otate around *,y+ not origin
get&otateInstance*%%%+ methods similar to a#ove
"caling
-ine thic$ness is scaled% If you don<t want this to happen, don<t modify
the ,raphics2D o#2ect, modify the shapes themselves
If you pass negative values, you can switch the direction of the ais
pu#lic void scale*dou#le s, dou#le y+
get"caleInstance*/+
)ode !ample, &otate%2ava
'ransforming shapes
pu#lic "hape create'ransformed"hape*"hape p"rc+
4ses an eisting Affine'ransform and transforms a given "hape and
returns the result as another "hape
"hear 'ransformations
Meaning of "hear
H "hear
If you specify a non9(ero shear, then values will #e more and more
shifted to the right the farther they are away from the y ais% .or eample,
an shear of 7%8 means that the value will #e shifted 87W of the
distance the point is away from the y ais%
> "hear
Points are shifted down in proportion to the distance they are away from
the ais%
)ode !ample, "hear%2ava
)reating transformed shapes
>ou can use Affine'ransforms to produce comple loo$ing graphics
fairly easily%
"tart with a #ase shape
&otate
"cale
'ransform
)reate modified versions of a .ont
"hear
'ranslate
3nce you ma$e a transformation, it can #e applied to any ,raphics2D
o#2ect
)ode !ample, Affine8%2ava
&endering =ints
Default?
.aster drawing
&endering =ints?
-et you re6uest more accurate *#ut generally slower+ drawing%
!ample *highest 6uality+?
5endering8ints render8ints
new 5endering8ints(5endering8ints.F&=/">;4"A4"S4>G$
5endering8ints.G"AH&/">;4"A4"S/(>);
...
public void paintComponent(Graphics g) {
!! super.paintComponent(g);
Graphics2D g2d (Graphics2D)g;
g2d.set5endering8ints(render8ints);
3ther 1ays of "etting &endering =ints
,ava IDswing.aate#ttrue B=our<ainClass.classJ
turns on anti9aliasing for everything in your app
&endering=ints is one trait that is passed from a parent to a child
container
"o, to turn on rendering hints for a container?
public void paint(Graphics g) {
Graphics2D g2d (Graphics2D)g;
5endering8ints render8ints
new
5endering8ints(5endering8ints.F&=/">;4"A4"S4>G$
5endering8ints.G"AH&/">;4"A4"S/(>);
g2d.set5endering8ints(render8ints);
super.paint(g2d);
'
In practice, the Enew &endering=intsF would #e a static final attri#ute on
the o#2ect, and not made new each time in a paint method%
Images
An Image is a two9dimensional array of colors% !ach element is called
a piel
2ava%awt%Image is effectively 2ust a #o for image data, you can read
from it, #ut not modify it%
>ou can load Images using a Media'rac$er o#2ect, shown earlier
3riginal ,raphics support in A1' supplied si methods to draw
images
3ne pair to draw at a given location
'he second to draw scaled image
'he third pair to draw into a clipped rectangle
Java 2D adds the following
3ne method to run the Image through an Affine'ransform
3ne method to draw a processed 0ufferedImage%
3ptions on drawing Images
All of the 2D #ehaviors can #e applied to drawing images
'ransforms
)lipping
Alpha
If you ma$e a 0ufferedImage, you can get a ,raphics2D contet from
that and draw directly on the image
Image Processing
0lurring
"harpening
!dge Detecting
Posteri(ing
Inversion
0rightness
)olor )onversions
Devices in Java2D
3ne goal of the 2D API is to ma$e the rendering process the same,
regardless of the output device%
,raphics!nvironment
Onows a#out fonts on your computer
)an access screen devices *,raphicsDevice class+
'>P!M&A"'!&M")&!!D
'>P!MP&ID'!&
'>P!MIMA,!M04..!&
Default Affine'ransforms
Printing
'uc$ed away in the 2ava%awt%print pac$age
Dot to #e confused with the A1' versions which are still includedV
2ava%awt%PrintJo# etc%%%
Oey classes for printing
2ava%awt%print%PrinterJo#
)ontrols the printing process, displays print dialog and page setup dialogs
2ava%awt%print%Printa#le
Interface represents something that can #e printed, contains a single method,
print*+
Printing "e6uence
.irst a PrinterJo# is instantiated #y calling the
PrinterJo#%getPrinterJo#*+ method
'he item to #e printed is then passed to the PrinterJo#<s setPrinta#le*+
method
A Print dialog is then shown
If the user presses o$, the printDialog*+ method returns true, and the
print 2o# is started #y calling the PrinterJo# print*+ method
)ontrol is returned to the application once the entire printing 2o# has
#een sent to the underlying 3"%
'he Printa#le Interface
"ingle method which must #e implemented #y o#2ect #eing printed

public int print(Graphics g$ 9age0ormat pf$ int


page4nde#) throws 9rinter&#ception
)alled to render a page to a printer
>ou can cast the Graphics o#2ect to a Graphics2D o#2ect to ta$e
advantage of 2D<s features
Page.ormat descri#es the si(e and orientation of the paper
pageInde is the num#er of the page to #e printed
"hould return 9"G&/&)4S;S if everything is o$, >(/SHC8/9"G& if
not
Declaring the eception in your method is optional
Page.ormat class
Descri#es a sheet of paper and its orientation
7,7 is at top left
Imagea#le area is the part of the paper on which the printer can print
'hree orientations
P3&'&AI'
-ADD")AP! *7,7 at #ottom left+
&!N!&"!M-ADD")AP! *7,7 at top right+
get1idth and get=eight methods return 8:52nd inches
B%C 88 is @82 5X2 units
PrinterJo# class
Do pu#lic constructor, use factory method
setPrinta#le*Printa#le painta#le+ sets the o#2ect to #e printed
print*+ starts the print 2o#
cancel*+ stops it as soon as possi#le, #ut needs to #e in a separate
thread%
"howing Dialogs
printDialog*+ #rings up options on printer, num#er of copies, and page
range%
If user selects 3O, the method returns true
pageDialog*+ #rings up options on page si(e and orientation
returns a Page.ormat o#2ect%
Printing "wing components
JDO 8%2 had a lot of printing pro#lems%
"wing containers automatically implement dou#le #uffering
'he offscreen image that is used for dou#le #uffering has the same
resolution as the screen *typically 52dpi+%
If you print to a A77 dpi printer, you effectively get a screen dump as pictured
in Print'est8%2ava
All you need to do is disa#le dou#le #uffering during paint
In JDO8%AJ, the dou#le #uffering pro#lem is fiedV *Print'estA%2ava+
Printing in the modern JDO
J)omponent previously did not override print% 'his meant that printing
was no different than painting, resulting in the dou#le #uffer #eing
used #y default%
'o #e consistent with the painting methods, methods print0order,
print)hildren and print)omponent have #een added, all of which are
protected%
'his means that the print method of a J)omponent does the following?
Invo$e this method to print the receiver% 'his method will result in
invocations to print)omponent, print0order and print)hildren%
It is not recommended that you override this method, instead override one
of the previously mentioned methods%
'his method sets the receivers state such that the dou#le #uffer will not #e
used, eg painting will #e done directly on the passed in ,raphics%
)ode eample, Print'estA%2ava
Printing Multiple Pages

9rinterKob #lindly call print interface in Printa#le o#2ect until


>(/SHC8/9"G& is returned%
All pages will have same page setup

9ageable interface
specifies a way to associate a 9age0ormat and a 9rintable with
each page of a print 2o#%
,ava.awt.print.*oo+ implements this interface
Downloads
,et the presentation at http?::we#dev%apl%2hu%edu:Y
r#e:2ava:JavaM2D:all%(ip

Вам также может понравиться