且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

旋转和裁剪图像IOS

更新时间:2023-11-10 10:15:46

使用以下代码段来旋转图像数据。

Use the following snippet for rotating image data.

输入数据是 inAngle (弧度角)和 inImage UIImage 实例)。

The input data is inAngle (angle in radians) and inImage (UIImage instance).

这样做,它会创建一个图像上下文,将转换应用于它将原始图像绘制到该上下文中。生成的图像数据现在将存储在 resultImage 中。

What this does, it creates an image context, applies the transformation to it and draws the original image into that context. The resulting image data will now be stored in resultImage.

前三行处理边界结果的计算图像框架。

The first three lines handle the calculation of the bounding result image frame.

UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, inImage.size.width, inImage.size.height)];
rotatedViewBox.transform = CGAffineTransformMakeRotation(inAngle);
CGSize rotatedSize = rotatedViewBox.frame.size;

UIGraphicsBeginImageContext(rotatedSize);
CGContextRef bitmap = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(bitmap, rotatedSize.width / 2.0f, rotatedSize.height / 2.0f);
CGContextRotateCTM(bitmap, inAngle);
CGContextScaleCTM(bitmap, 1.0f, -1.0f);
CGContextDrawImage(bitmap, CGRectMake(-inImage.size.width / 2.0f,
                                      -inImage.size.height / 2.0f,
                                      inImage.size.width,
                                      inImage.size.height),
                                      inImage.CGImage);
UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();