On Feb 28, 2009, at 10:20 PM, Jerry Krinock wrote:

On 2009 Feb 28, at 20:10, Graham Cox wrote:

Create the new image, swapping width and height, lock focus onto it, apply a transform that rotates 90 degrees, and draw the first into the second.

You can't do it without drawing, but the drawing doesn't need to be onscreen.

Thanks, Graham.  Fun stuff....

@implementation NSImage (Transform)
[snip]
@end

That version only works for a ±90° rotation since you're just swapping the width and height for the rotated image size. A more generalized solution would be:

- (NSImage*)imageRotatedByDegrees:(CGFloat)degrees
{
    // calculate the bounds for the rotated image
    NSRect imageBounds = {NSZeroPoint, [self size]};
NSBezierPath* boundsPath = [NSBezierPath bezierPathWithRect:imageBounds];
    NSAffineTransform* transform = [NSAffineTransform transform];

    [transform rotateByDegrees:degrees];
    [boundsPath transformUsingAffineTransform:transform];

    NSRect rotatedBounds = {NSZeroPoint, [boundsPath bounds].size};
NSImage* rotatedImage = [[[NSImage alloc] initWithSize:rotatedBounds.size] autorelease];

    // center the image within the rotated bounds
imageBounds.origin.x = NSMidX(rotatedBounds) - (NSWidth (imageBounds) / 2); imageBounds.origin.y = NSMidY(rotatedBounds) - (NSHeight (imageBounds) / 2);

    // set up the rotation transform
    transform = [NSAffineTransform transform];
[transform translateXBy:+(NSWidth(rotatedBounds) / 2) yBy:+ (NSHeight(rotatedBounds) / 2)];
    [transform rotateByDegrees:degrees];
[transform translateXBy:-(NSWidth(rotatedBounds) / 2) yBy:- (NSHeight(rotatedBounds) / 2)];

    // draw the original image, rotated, into the new image
    [rotatedImage lockFocus];
    [transform set];
[self drawInRect:imageBounds fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0] ;
    [rotatedImage unlockFocus];

    return rotatedImage;
}

_______________________________________________

Cocoa-dev mailing list ([email protected])

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [email protected]

Reply via email to