views:

483

answers:

1

I have a window with an subclass of NSView in it. Inside the view, I put an NSImage.

I want to be able to rotate the image by 90 degrees, keeping the (new) upper left corner of the image in the upper left corner of the view. Of course, I will have to rotate the image, and then translate it to put the origin back into place.

In Carbon, I found CGContextRotateCTM which does what I want . However, I can't find the right call in ObjC. setFrameCenterRotation doesn't seem to do anything, and in setFrameRotation, I can't seem to figure out where the origin is, so I can approprately translate.

It seems to move. When I resize the window it puts the image (or part of it, I seem to have a strange clipping issue as wel) and when I scroll, it jumps to a different (and not always the saem) location.

Does this make sense to anyone?

thanks

+2  A: 

I rotate text on the screen for an app I work on and the Cocoa (I assume you mean Cocoa and not ObjC in your question) way of doing this is to use NSAffineTransform.

Here's a snippet that should get you started

double rotateDeg = 90;
NSAffineTransform *rotate = [[NSAffineTransform alloc] init];
NSGraphicsContext *context = [NSGraphicsContext currentContext];

[context saveGraphicsState];
[rotate rotateByDegrees:rotateDeg];
[rotate concat];

    /* Your drawing code [NSImage drawAtPoint....]for the image goes here 
       Also, if you need to lock focus when drawing, do it here.       */

[rotate release];
[context restoreGraphicsState];

The mathematics on the rotation can get a little tricky here because what the above does is to rotate the coordinate system that you are drawing into. My rotation of 90 degrees is a counter-clockwise rotation.

Jeff Hellman
Yes, I meant Cocoa, thanksSo, should I just have to do the above, and then [view setNeedsDisplay:YES]? I know that setNeedsDisplay makes the view call drawRect:, which does the drawing work... because nothing seems to happen when I do that.
Brian Postow
The code snippet I put in above should actually be in the drawRect: method of your NSView subclass. The NSAffineTransform needs to run each time the view is redrawn.
Jeff Hellman
Excellent! Now I just need to figure out how the translation works. after I translate, I'm having issues with changing the rectangles so things actually display correctly...
Brian Postow
The Cocoa and Core Graphics Drawing Guides both explain co-ordinate transformations very well. It's well worth reading both of them.
Peter Hosey