Java Reference
In-Depth Information
This class must meet the minimal requirements of the
CustomItem
interface by imple-
menting a constructor that calls the inherited constructor, providing layout hints to the
layout manager via the
getPref
and
getMin
dimension methods, and providing a
paint
method that draws the contents of the item.
The
SVGImageItem
constructor method in Listing 16-13 is a little more involved
than the pseudocode in Listing 16-12, because it uses an
SVGAnimator
to obtain preferred
bounds for the SVG image. I create an
SVGAnimator
, which would render on a
Canvas
, and
then get the preferred bounds of that
Canvas
instance. After I do this, I just discard the
Canvas
instance and
SVGAnimator
, because I won't need it for anything else. Finally, I
set the image's
viewport
—its bounds—to the preferred bounds I obtained from the
SVGAnimator
's
Canvas
instance.
■
Note
While it's possible to determine an SVG image's bounds by using the
SVGDocument
methods to
access the DOM of the SVG image directly, using an
SVGAnimator
is clearer and will pave the way for you to
understand how to animate an SVG image, which I show you in the next section.
The MIDP layout manager uses the
getPrefContentHeight
and
getPrefContentWidth
methods to determine the SVG image's preferred height and width, respectively, as com-
puted by the constructor. When the layout manager wants to obtain a preferred bound
for width or height, it passes the appropriate method a desired bound for the
other
axis.
The
getMinContentHeight
and
getMinContentWidth
methods return the preferred bounds
for the image.
The
paint
method performs the same basic work as the pseudocode in Listing 16-12.
First, it paints an empty rectangle where it will paint the SVG image, in case something
was on the screen at that location. Next, it binds the
ScalableGraphics
instance to the
Graphics
instance that the containing
Canvas
provided to the
paint
method. This provides
the
ScalableGraphics
instance with a
GraphicContext
to use when rendering the SVG
image. After that, it sets the image's actual width and height to the width and height pro-
vided by the containing
Canvas
, and then it tells the
ScalableGraphics
instance to render
the image at the origin of the item. Finally, it releases the
Graphics
context bound using
the
ScalableGraphics
's
releaseTarget
method.
Rendering Animated SVG Images
The second way to render an
SVGImage
, using an
SVGCanvas
, is a little more work, but it lets
you easily render animated SVG images or those that process events. The strategy is simi-
lar to what you saw in Listing 16-13:
1.
Create an instance of
SVGImage
representing the image you want to draw.
2.
Create an instance of
SVGAnimator
with the
SVGImage
.