UIImage旋转
问题描述:
我在UIImageView(在UIScrollView中)中显示图像,该图像也存储在CoreData中。UIImage旋转
在界面中,我希望用户能够将图片旋转90度。我也希望它被保存在CoreData中。
我应该在显示屏上旋转什么? scrollview,uiimageview或图像本身? (如果可能,我想旋转动画)但是,我还必须将图片保存到CoreData。
我想过改变图像的方向,但这个属性是只读的。
答
要只显示旋转的图像,您应该旋转UIImageView。
您可以在CoreData中存储一些元数据以及图片,说明应该应用什么样的旋转。
某些图像格式具有隐式旋转属性。如果你知道压缩的图像数据格式,你可以查看规格并查看它是否支持它。
如果您要实际旋转图像像素,则必须手动执行此操作。您可以创建一个CGBitmapContext,并通过与变换矩阵混合来将图像绘制到其中,然后从位图创建一个新图像。
答
对于动画通过将其旋转乌尔ImageView的:
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
[UIView setAnimationRepeatAutoreverses:NO];
[UIView setAnimationRepeatCount:0];
imageViewObject.transform = CGAffineTransformMakeRotation(angle);
[UIView commitAnimations];
,当你保存图像为核心的数据,然后保存图像之前旋转该图像从当前位置imageViewRotated角度。 旋转UIImage使用这个://记住角度应该是弧度,如果它不是弧度然后将角度转换成弧度。
- (UIImage*) rotateInRadians:(float)radians
{
const size_t width = self.size.width;
const size_t height = self.size.height;
CGRect imgRect = (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = height};
CGRect rotatedRect = CGRectApplyAffineTransform(imgRect, CGAffineTransformMakeRotation(radians));
/// Create an ARGB bitmap context
CGContextRef bmContext = CreateARGBBitmapContext(rotatedRect.size.width, rotatedRect.size.height, 0);
if (!bmContext)
return nil;
CGContextSetShouldAntialias(bmContext, true);
CGContextSetAllowsAntialiasing(bmContext, true);
CGContextSetInterpolationQuality(bmContext, kCGInterpolationHigh);
/// Rotation happen here (around the center)
CGContextTranslateCTM(bmContext, +(rotatedRect.size.width * 0.5f), +(rotatedRect.size.height * 0.5f));
CGContextRotateCTM(bmContext, radians);
/// Draw the image in the bitmap context
CGContextDrawImage(bmContext, (CGRect){.origin.x = -(width * 0.5f), .origin.y = -(height * 0.5f), .size.width = width, .size.height = height}, self.CGImage);
/// Create an image object from the context
CGImageRef rotatedImageRef = CGBitmapContextCreateImage(bmContext);
UIImage* rotated = [UIImage imageWithCGImage:rotatedImageRef];
/// Cleanup
CGImageRelease(rotatedImageRef);
CGContextRelease(bmContext);
return rotated;
}
我希望这可以帮助你。
我实际上存储图像为JPEG,我认为它支持方向。但我可以从Cocoa访问吗? – Kamchatka 2010-05-17 03:49:38