旋转和裁剪图像IOS [英] Rotation and cropping an image IOS

查看:300
本文介绍了旋转和裁剪图像IOS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 UIImageView 上执行旋转,然后我尝试裁剪它的一部分并将其保存为 UIImage UIImageView 会旋转,但它总是裁剪照片的相同部分。因此裁剪不考虑图像旋转。我究竟做错了什么?

I am performing rotation on an UIImageView and then i try to crop a part of it and save it as an UIImage. The UIImageView rotates however it always crops the same part of the photo. So the cropping does not take into account the image rotation. What am i doing wrong?

//rotate image 
CGRect new = CGRectMake(0, 0, 100, 50);
CGAffineTransform rotation = CGAffineTransformMakeRotation(5);
[photo setTransform:rotation];

// crop image 
CGImageRef imageRef = CGImageCreateWithImageInRect([photo.image CGImage], new);
UIImage *croppedImage = [UIImage imageWithCGImage:imageRef]; 
CGImageRelease(imageRef);

// display crop bounds 
UIView* faceBounds = [[UIView alloc] initWithFrame:new];
faceBounds.layer.borderWidth = 2;
faceBounds.layer.borderColor = [[UIColor redColor] CGColor];


推荐答案

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

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();

这篇关于旋转和裁剪图像IOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆