在實際專案中,我們經常需要對圖片進行各種處理,以達到效能優化或滿足特定需求。以下整理五種最常見的圖片處理場景。
專案中使用的圖片素材,如果能透過拉伸獲得就盡量這樣做。這麼做有兩個好處:一是能減少 App 安裝包的大小,二是能降低運行時佔用的記憶體。畢竟 App 的 UI 大多建立在大量精緻的圖片上,若一律使用與螢幕等大的圖片,對效能與安裝量都會帶來负面影响。
對於拉伸圖片,適配 iOS 5 及之後版本可使用 resizableImageWithCapInsets:。這個方法只接收一個 UIEdgeInsets 型別的參數,透過設定 top、left、bottom、right 分別指定上、左、下、右端蓋的距離,單位為 pt。需要注意,若端蓋距離不是整數,拉伸後的圖片可能會出現白色細線。
如果有一張大圖,我們只想顯示指定大小的縮圖內容,可以在 UIImage 的分類中實作以下方法:
- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize {
UIImage *sourceImage = self;
UIImage *newImage = nil;
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;
CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;
CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;
if (widthFactor > heightFactor) scaleFactor = widthFactor;
else scaleFactor = heightFactor;
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
if (widthFactor > heightFactor) {
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
} else if (widthFactor < heightFactor) {
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
}
UIGraphicsBeginImageContext(targetSize);
CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;
[sourceImage drawInRect:thumbnailRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
if (newImage == nil) NSLog(@"could not scale image");
UIGraphicsEndImageContext();
return newImage;
}
使用系統相機拍照或從相簿選取圖片,直接上傳後在非 Mac 系統下檢視會發現圖片發生了旋轉,這是因為我們沒有依圖片的旋轉屬性修正方向。可用以下方法解決:
@interface UIImage (fixOrientation)
- (UIImage *)fixOrientation;
@end
@implementation UIImage (fixOrientation)
- (UIImage *)fixOrientation {
if (self.imageOrientation == UIImageOrientationUp) return self;
CGAffineTransform transform = CGAffineTransformIdentity;
switch (self.imageOrientation) {
case UIImageOrientationDown:
case UIImageOrientationDownMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height);
transform = CGAffineTransformRotate(transform, M_PI);
break;
case UIImageOrientationLeft:
case UIImageOrientationLeftMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, 0);
transform = CGAffineTransformRotate(transform, M_PI_2);
break;
case UIImageOrientationRight:
case UIImageOrientationRightMirrored:
transform = CGAffineTransformTranslate(transform, 0, self.size.height);
transform = CGAffineTransformRotate(transform, -M_PI_2);
break;
}
switch (self.imageOrientation) {
case UIImageOrientationUpMirrored:
case UIImageOrientationDownMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, 0);
transform = CGAffineTransformScale(transform, -1, 1);
break;
case UIImageOrientationLeftMirrored:
case UIImageOrientationRightMirrored:
transform = CGAffineTransformTranslate(transform, self.size.height, 0);
transform = CGAffineTransformScale(transform, -1, 1);
break;
}
CGContextRef ctx = CGBitmapContextCreate(NULL, self.size.width, self.size.height, CGImageGetBitsPerComponent(self.CGImage), 0, CGImageGetColorSpace(self.CGImage), CGImageGetBitmapInfo(self.CGImage));
CGContextConcatCTM(ctx, transform);
switch (self.imageOrientation) {
case UIImageOrientationLeft:
case UIImageOrientationLeftMirrored:
case UIImageOrientationRight:
case UIImageOrientationRightMirrored:
CGContextDrawImage(ctx, CGRectMake(0, 0, self.size.height, self.size.width), self.CGImage);
break;
default:
CGContextDrawImage(ctx, CGRectMake(0, 0, self.size.width, self.size.height), self.CGImage);
break;
}
CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
UIImage *img = [UIImage imageWithCGImage:cgimg];
CGContextRelease(ctx);
CGImageRelease(cgimg);
return img;
}
@end
有時我們需要將圖片資料以字串形式上傳到伺服器。在將 UIImage 轉為 NSData 再轉為 NSString 時,若未先編碼,NSString 中會出現亂碼。此時需先對 NSData 做 Base64 編碼:
#import "UIImage+Ext.h"
#import "GTMBase64.h"
@interface UIImage (Ext)
- (NSString *)convertToString;
@end
@implementation UIImage (Ext)
- (NSString *)convertToString {
if (!self) { return nil; }
NSData *imgData = UIImageJPEGRepresentation(self, 0.5);
NSData *encode = [GTMBase64 encodeData:imgData]; // Base64 編碼,解決亂碼
NSString *imgStr = [[NSString alloc] initWithData:encode encoding:NSUTF8StringEncoding];
return imgStr;
}
@end
要將圖片存到本地磁碟,需先將圖片物件轉為 NSData,再呼叫 writeToFile:atomically: 介面寫入:
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile;