I display an image in a UIImageView (within a 开发者_运维问答UIScrollView) which is also stored in CoreData.
In the interface, I want the user to be able to rotate the picture by 90 degrees. I also want it to be saved in CoreData.
What should I rotate in the display? the scrollview, the uiimageview or the image itself? (If possible I would like the rotation to be animated) But then I also have to save the picture to CoreData.
I thought about changing the image orientation but this property is readonly.
To just display the image rotated, you should rotate the UIImageView.
You could store some metadata along with the image in CoreData saying what rotation should be applied.
Some image formats have an implicit rotation property. If you know the compressed image data format you can look up the specification and see if it supports it.
If you are going to actually rotate the image pixels, you will have to do that manually. You can create a CGBitmapContext and draw the image into it rotated by messing with the transform matrix, then create a new image from the bitmap.
For the animation rotate ur ImageView by transforming it:
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
[UIView setAnimationRepeatAutoreverses:NO];
[UIView setAnimationRepeatCount:0];
imageViewObject.transform = CGAffineTransformMakeRotation(angle);
[UIView commitAnimations];
and when you save the image into core data, then before saving image rotate that image to angle imageViewRotated from current position. for rotating UIImage use this: //remember the angle should be in Radian, if it is not in radian then convert angle into radian.
- (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;
}
I hope this helps you.
精彩评论