
290
|
Chapter 8, Rendering
#56 Create a Magnifying Glass Component
HACK
With a grab rectangle calculated, call Robot.createScreenCapture( ) to grab
those pixels and return them as a
BufferedImage. Unless your zoom factor is
1.0
, this image will be larger or smaller than the
DetachedMagnifyingGlass
component, so you need to use
getScaledInstance( )
to scale it to your com-
ponent size. In terms of a scaling behavior, the code uses the
SCALE_FAST
constant because the moving mouse will be calling for many repaints, and
thus many grabs and scales, every second. Finally, with your properly sized
image in memory, you paint to the
Graphics to get the grabbed data into
your component.
One TODO item I haven’t shown here, but that might pro-
vide a performance boost, would be to
flush( ) the various
temporary images after you’ve called
drawImage( ).
To ensure the AWT LayoutManagers respect the size that’s set for the compo-
nent, have
getPreferredSize( ), getMinimumSize( ), and getMaximumSize( ) all
return the size that was originally sent to the constructor, since the size of
the magnifier component is critical in computing what to grab from the
source component.
The last bit of code in this class is a
MouseMotionListner, which is used to
track the mouse’s location. You need to do this so you’ll always have an up-
to-date point when the
paint( ) method is called. You’ll only get events
when the cursor is over the source ...