Rotating CIImage around a point

1.3k views Asked by At

I would like to rotate a UIImage from file (a jpeg on the file system) a computed amount of radians, but I would like to rotate it around a point in the image, as well as keep the original size of the image (with transparent gaps in the image where image data no longer exists, as well as cropping image data that has moved outside of the original frame). I would like to then store and display the resulting UIImage. I haven't found any resources for this task, any help would be much appreciated!

The closest thing I have found so far (with some slight modifications) is as follows:

-(UIImage*)rotateImage:(UIImage*)image aroundPoint:(CGPoint)point radians:(float)radians newSize:(CGRect)newSize { CGRect imageRect = { point, image.size };

UIGraphicsBeginImageContext(image.size);

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, imageRect.origin.x, imageRect.origin.y);
CGContextRotateCTM(context, radians);
CGContextTranslateCTM(context, -imageRect.origin.x, -imageRect.origin.y);
CGContextDrawImage(context, (CGRect){ CGPointZero, imageRect.size }, [image CGImage]);
UIImage *returnImg = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();
return returnImg;

}

Unfortunately, this rotates the image incorrectly (in my tests, somewhere in the neighborhood of 180 degrees more than desired).

1

There are 1 answers

1
EmilDo On

to rotate that UIImage image, lets say 90 degrees, you can easily do:

imageView.transform = CGAffineTransformMakeRotation(M_PI/2);

to rotate it multiple times you can use:

UIView animateKeyframesWithDuration method 

and to anchor it to some point you can use:

[image.layer setAnchorPoint:CGPointMake(....)];