Skip to main content

Zoom in and out

3 replies [Last post]
kiths
Offline
Joined: 2010-06-15
Points: 0

Hi,

I am working on a Java project, based on calibrations, I generate a graph for which I need to implement the feature Zoom in and out. I must make it enlarge and small when the mouse scroll / wheel is moved up and down, or provide an option to enlarge when it is doubled clicked (like how it appears in windows image viewer)

Is this feasible to do. Could someone share their thoughts on this, so that I can get started.

Thanks,
K

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
kitfox
Offline
Joined: 2004-03-31
Points: 0

This is actually fairly easy. First, create something that extends JComponent that will draw the image in its paintComponent(Graphics g) method. Also add a 'double' property to this class called 'zoom'. Whenever the paint component method is called, call g.scale(zoom, zoom); on its Graphics object before drawing the image.

To get the scrollpane to respond properly, make sure your class implements Scrollable. Also, whenever the zoom property is changed, make sure to setPreferredSize() to the new zoomed size of the image and then call revalidate().

cradle
Offline
Joined: 2004-09-29
Points: 0

> Whenever the paint component method is called, call
> g.scale(zoom, zoom); on its Graphics object before
> drawing the image.

One caveat with this method: Everything will be scaled, including line stroke widths, character glyphs, etc. So if your graph line width is 2 pixels initially, and you zoom in by a factor of 20, your graph line will now be 40 pixels wide -- probably not what you wanted.

charetjc
Offline
Joined: 2004-07-24
Points: 0

If you want to avoid scaling everything, then use the AffineTransform instead of the Graphics transform methods.

[code]
public void paintComponent (Graphics g) {
Graphics2D g2 = (Graphics2D) g;
AffineTransform transform = new AffineTransform();
Path2D.Double plot = new Path2D.Double(); // or use GenericPath/Path2D.Float for single float precision
Shape shape;

transform.scale( scaleX, scaleY ); // scaleX and scaleY can be your class attributes/fields/variables/etc

//... create your curve using the plot here, or create the path before the repaint() and save the Path in class variable for use here...
shape = transform.createTransformedShape( plot );
g2.draw( shape );
}
[/code]