iOS rotate UIImage using Quartz

2019-09-17 22:24发布

问题:

I have a UIView subclass with custom

- (void)drawRect:(CGRect)rect

I want to draw an UIImage at position 50,50 and have it rotated by 20 degrees.
I tried the following code:

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextRotateCTM (context, degreesToRad(20));
[image drawAtPoint:CGPointMake(50, 50)];
CGContextRestoreGState(context);

It rotates the image correctly, but it is not at 50,50...
How can I rotate an UIImage while maintaining the correct coordinates?

回答1:

Why are You using drawRect to draw Image?

UIImageView is optimized enough to be as fast as possible, so You could use something like this:

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 / 20.0 * M_PI );

[imageView setTransform:rotate];