Fighting with computers

Computers are not always friendly.

Tuesday, August 13, 2013

Flipping a vector drawing in Java

An ongoing project required some 2D vector paths to be mirrored. I was programming in Java and using Area object to represent these paths. Though the obvious thing was to do this myself, I turned to the libraries for help.  I have not used AffineTransform before, but it seemed the right tool for the job. Unfortunately, either my understanding is shrinking (which may well be the case) or the existing documentation is not good enough.

After trying several matrices from different posts online I realized I was not getting any closer to a good solution. The main problem is that while you can mirror an Area object with just one matrix (-1,0,0,1,0,0) you can't avoid the translation that will happen at the same time.

The solution to my problem ended up being quite simple (I wanted to mirror the image in the X axis).

// object a is the area I want to flip
AffineTransform at = new AffineTransform();
at.scale(-1,1);
Rectangle r = a.getBounds();
at.translate(-( r.width + 2 * r.x ), 0.0);
a.transform(at); 

This way I create an affine transform that using scale method will create the mirrored image that later will be restored to its original location by means of a translation. I wish I had found something like this before.

6 Comments:

Post a Comment

<< Home