views:

38

answers:

2

I would like to be able to zoom and unzoom on a Java2D scene made of Path2D.Double without thickening the lines, just by dilating the distances.

I'v tried to apply a transformation to the Graphics2D object the paintComponent method receives, but this makes the lines thicker. The only way I found was to apply a transformation to the lines (line.transform(AffineTransform.getScaleInstance(2d,2d)) for instance) but every time I zoom and unzoom again, I lose information because of floating point errors.

To make a long story short: the transformations are destructive. is there a way to say "i want to draw this line with that transformation applied without modifying the content of the line"?

A: 

As you found, changing the Graphics2D transform affects all drawing, but nothing precludes saving, modifying and restoring the transform inside paintComponent(). In this example, the content is drawn in a scaled context, while a Rectangle.Double surrounding the target object is drawn unscaled.

Addendum: The example uses explicit transformations, but you can use AffineTransform, instead. Like Rectangle2D, Path2D implements the Shape interface, so you can use createInverse() and createTransformedShape(), accordingly. Here's a related example.

trashgod
I saw that I could save a transformation and restore it later for what concerns Graphics2D but I what I would like to do can be reformulated as doing the same with a Path2D.
Paul Brauner
@Paul Brauner: You can use `AffineTransform` on `Path2D`, as suggested above.
trashgod
yep, but then it modifies the Path2D, that's the whole point, I would like to be able to apply it to a Path2D and get a new one without modifying the original one
Paul Brauner
@Paul Brauner: I'd think you could use the copy constructor, `Path2D.Double(Shape s, AffineTransform at)`, to copy and transform the original.
trashgod
+1  A: 

I found the solution: I change the line width according to the scale factor in Graphic2D, that way I can apply the transform to Graphic2D itself and it doesn't destruct the original coordinates contained in the Path2D.

tr = g.getTransform()
g.transform(AffineTransform.getScaleInstance(scaleFactor,scaleFactor))
g.setStroke(new java.awt.BasicStroke(1.0f/scaleFactor.toFloat))
/* draw lines */
g.setTransform(tr)
Paul Brauner