原以為伺服器吐回來給我的會是「直向」的圖,那麼我就可以不去旋轉它,但事與願違,我還是得處理「橫向」的圖⋯⋯好在吐回來的圖像資料,除了有URL外,還有Orientation,那麼我就根據後者去判斷是否該旋轉90度!
把以下的code貼到想要使用的.m檔內即可:)~
/**
Theme: Image Rotation
IDE: Xcode 6
Language: Objective C
Date: 103/10/02
Author: HappyMan
Blog: https://cg2010studio.wordpress.com/
*/
@interface UIImage (RotationMethods)
- (UIImage *)imageRotatedByDegrees:(CGFloat)degrees;
@end
@implementation UIImage (RotationMethods)
static CGFloat DegreesToRadians(CGFloat degrees) {return degrees * M_PI / 180;};
- (UIImage *)imageRotatedByDegrees:(CGFloat)degrees
{
// calculate the size of the rotated view's containing box for our drawing space
UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.size.width, self.size.height)];
CGAffineTransform t = CGAffineTransformMakeRotation(DegreesToRadians(degrees));
rotatedViewBox.transform = t;
CGSize rotatedSize = rotatedViewBox.frame.size;
// Create the bitmap context
UIGraphicsBeginImageContextWithOptions(rotatedSize, NO, 2.0);
CGContextRef bitmap = UIGraphicsGetCurrentContext();
// Move the origin to the middle of the image so we will rotate and scale around the center.
CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);
// Rotate the image context
CGContextRotateCTM(bitmap, DegreesToRadians(degrees));
// Now, draw the rotated/scaled image into the context
CGContextScaleCTM(bitmap, 1.0, -1.0);
CGContextDrawImage(bitmap, CGRectMake(-self.size.width / 2, -self.size.height / 2, self.size.width, self.size.height), [self CGImage]);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
@end
使用方式相當簡單,只要以UIImage的實體來呼叫此方法,然後它處理完會吐回UIImage。
UIImage *rotatedImage = [happyImage imageRotatedByDegrees:90.0];
如此就可以旋轉90度囉~當然你想轉180度、246度等等也是可以!
要注意的是,這裡不是UIImageView的做法喔!因為我想要直接轉存成檔案,所以是用UIImage來做到。
參考:StackOverFlow – How to rotate an image 90 degrees on iOS?。
隨意留個言吧:)~