Lee Armstrong
Lee Armstrong

Reputation: 11452

Rotate UIImage in drawRect

I have the following code that displays an image when the drawRect is called.

  UIImage *sourceImage = [UIImage imageNamed:@"icon.png"];    


CGRect rect = CGRectMake(12.5, 12.5, 
                         sourceImage.size.width, 
                         sourceImage.size.height);

[sourceImage drawInRect:rect];

How can I get this rotated by a number of degrees before it gets drawn, everything I read needs it in a ImageView which seems heavy in a drawRect

Upvotes: 0

Views: 4080

Answers (2)

Erik Tjernlund
Erik Tjernlund

Reputation: 1983

Rotating (or any other transformation done by a transformation matrix) is not "heavy". All the transforms basically are simple multiplications of a vector and a small matrix (see Apple's Quartz 2D documentation for the math)

Use CGContextRotateCTM(context, radians); before you draw the image with [sourceImage drawInRect:rect];. If you need to rotate the image around another point, translate with CGContextTranslateCTM first.

Upvotes: 4

Kirby Todd
Kirby Todd

Reputation: 11546

UIImage *image = [UIImage imageNamed:@"icon.png"];
UIImageView *imageView = [ [ UIImageView alloc ] initWithFrame:CGRectMake(0.0, 0.0, image.size.width, image.size.height) ];
imageView.image = image;
[self addSubview:imageView];
CGAffineTransform rotate = CGAffineTransformMakeRotation( 1.0 / 180.0 * 3.14 );
[imageView setTransform:rotate];

Upvotes: 6

Related Questions