我有一个UIImageView控件,其中包含一张图片。在显示之前,通过将UIImageView的transform属性设置为CGAffineTransformMakeRotation(angle),其中angle为弧度角度,来旋转图像。
我希望能够创建另一个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;
}
然而,图像并没有围绕其中心旋转。我已经尝试了所有可能的变换组合来使它围绕中心旋转,但是无济于事。我是否漏掉了什么技巧?由于我旋转的是上下文而不是图像,所以这是否可能?
现在很渴望让它工作,任何帮助将不胜感激。
Dave
编辑:我已被要求多次提供我的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