我有一个UIImageView和一个图像。我通过将UIImageView的transform属性设置为CGAffineTransformMakeRotation(angle)(其中angle是以弧度表示的角度)来旋转图像。从旋转的UIImageView创建UIImage
我希望能够创建另一个UIImage,它对应于我在我看来可以看到的旋转版本。
我几乎没有,通过旋转图像方面,我得到一个旋转的图像:
- (UIImage *) rotatedImageFromImageView: (UIImageView *) imageView
{
UIImage *rotatedImage;
// Get image width, height of the bounding rectangle
CGRect boundingRect = [self getBoundingRectAfterRotation: imageView.bounds byAngle:angle];
// Create a graphics context the size of the bounding rectangle
UIGraphicsBeginImageContext(boundingRect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
// Rotate and translate the context
CGAffineTransform ourTransform = CGAffineTransformIdentity;
ourTransform = CGAffineTransformConcat(ourTransform, CGAffineTransformMakeRotation(angle));
CGContextConcatCTM(context, ourTransform);
// Draw the image into the context
CGContextDrawImage(context, CGRectMake(0, 0, imageView.image.size.width, imageView.image.size.height), imageView.image.CGImage);
// Get an image from the context
rotatedImage = [UIImage imageWithCGImage: CGBitmapContextCreateImage(context)];
// Clean up
UIGraphicsEndImageContext();
return rotatedImage;
}
但是图像不绕其中心旋转。我已经尝试了各种与我的旋转连接的变换,以使它围绕中心旋转,但无济于事。我错过了一招吗?这是甚至可能的,因为我旋转的上下文而不是图像?
越来越绝望的做出这项工作,所以任何帮助将不胜感激。
戴夫
编辑:我已经多次询问我boundingRect代码,所以在这里它是:
- (CGRect) getBoundingRectAfterRotation: (CGRect) rectangle byAngle: (CGFloat) angleOfRotation {
// Calculate the width and height of the bounding rectangle using basic trig
CGFloat newWidth = rectangle.size.width * fabs(cosf(angleOfRotation)) + rectangle.size.height * fabs(sinf(angleOfRotation));
CGFloat newHeight = rectangle.size.height * fabs(cosf(angleOfRotation)) + rectangle.size.width * fabs(sinf(angleOfRotation));
// Calculate the position of the origin
CGFloat newX = rectangle.origin.x + ((rectangle.size.width - newWidth)/2);
CGFloat newY = rectangle.origin.y + ((rectangle.size.height - newHeight)/2);
// Return the rectangle
return CGRectMake(newX, newY, newWidth, newHeight);
}
这是什么'getBoundingRectAfterRotation'函数? – bmdhacks 2011-11-12 04:37:30
嗨@bmdhacks getBoundingRectAfterRotation是我创建的一个方法,所以你不会在任何Cocoa-Touch类中找到它。它将一个直角和一个角度作为参数,并返回一个新的CGRect,如果它以给定的角度旋转,它将包含原始矩形。 – 2011-11-13 22:30:38
Hi @bmdhacks由于受欢迎的需求已添加编辑方法到我原来的问题。 – 2011-11-22 12:19:18