我有一個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