0%

iOS中通过CGContext实现图片围绕任意点旋转任意角度的功能

需求

需要围绕任意点旋转若干角度返回和原始图片大小相同的图片。

实现

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
+ (UIImage *)getRotationImage:(UIImage *)image rotation:(CGFloat)rotation point:(CGPoint)point {
NSInteger num = (NSInteger)(floor(rotation));
if (num == rotation && num % 360 == 0) {
return image;
}
double radius = rotation * M_PI / 180;

CGSize rotatedSize = image.size;
// Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize);
CGContextRef bitmap = UIGraphicsGetCurrentContext();

// rotated image view
CGContextScaleCTM(bitmap, 1.0, -1.0);

// move to the rotation relative point
CGContextTranslateCTM(bitmap, point.x, -point.y);

// Rotate the image context
CGContextRotateCTM(bitmap, radius);

// Now, draw the rotated/scaled image into the context
CGContextDrawImage(bitmap, CGRectMake(-point.x, -image.size.height+point.y, image.size.width, image.size.height), [image CGImage]);

UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}

输入:需要旋转的图片,旋转的角度,和旋转围绕的点。
返回:旋转后同样大小的结果图片。

调试CGContext的时候需要注意几点,设置的CGContextScaleCTM, CGContextTranslateCTM, CGContextRotateCTM等方法改变的是上下文的坐标系参数;不同的设置顺序返回的最终自定义的坐标系结果也是不尽相同。
在调适的时候,由于设计的坐标系调整相对复杂,对已有的方法做调整可能牵一发而动全身,无法知道之间的必然联系。建议先思考自己需要的图片调整结果的理想步骤,再逐步实现并测试每步步骤,一步步达到最终效果。😂不过应该是我不太熟悉,调了好久,期间都快挠破头皮,最终才实现需要的效果。

Reference

CGContext图形上下文详解
CGContext-上下文(画布)的应用