Rotate Scale Flip – NSImageView

This is a problem which I have fiddled a lot to solve. Sometimes NSImageView objects seems to behave strangely when you rotate them and try to reposition it inside its superview.

The Problem:
I had an NSImageView as subview of another NSView. There where slider controls to scale and rotate the subview as and when required. I also had horizontal and vertical flipping options. So when I played around with it, the subview started acting weirdly.

I had used [subview setFrameCenterRotation:angle]; to rotate the subview.
For flipping NSAffineTransform scaleXBy:yBy: was helpful. Scaling I had set the imageScaling flag,
so that I just have to set the frame and NSImageView takes care of it by itself.

Now why is this acting weirdly? Seems all fine. All proper apis have been used. After some brain wracking and a little help from OpenGL transformation application, I found out the solution.

If you have rotated a image view, before doing any other transformation rotate it back to zero angle and the apply the transforms and then rotate it back to required angle.

Code for flipping images:

- (void)flipImageVertically:(NSImageView*)imageView
{
NSAffineTransform *flipper = [NSAffineTransform transform];
NSSize dimensions = [imageView frame].size;

NSImage *aFrame = [imageView.image copy];

[aFrame lockFocus];
[flipper scaleXBy:1.0 yBy:-1.0];
[flipper set];

[aFrame drawAtPoint:NSMakePoint(0,-dimensions.height)
fromRect:NSMakeRect(0,0, dimensions.width, dimensions.height)
operation:NSCompositeCopy fraction:1.0];

[aFrame unlockFocus];

[imageView setImage:aFrame];

[aFrame release];

}

- (void)flipImageHorizontally:(NSImageView*)imageView
{
NSAffineTransform *flipper = [NSAffineTransform transform];
NSSize dimensions = [imageView frame].size;

NSImage *aFrame = [imageView.image copy];

[aFrame lockFocus];
[flipper scaleXBy:-1.0 yBy:1.0];
[flipper set];

[aFrame drawAtPoint:NSMakePoint(-dimensions.width,0)
fromRect:NSMakeRect(0,0, dimensions.width, dimensions.height)
operation:NSCompositeCopy fraction:1.0];

[aFrame unlockFocus];

[imageView setImage:aFrame];

[aFrame release];
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s