non-destructive transformations on java2d objects
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 th开发者_如何学编程e 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"?
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)
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.
精彩评论