iOS 中對圖片的處理離不開 UIImage,它繼承自 NSObject。下面依「取得圖片、初始化、繪製」三類,整理常用方法與屬性。
最常用的是用檔名取得已匯入專案的圖片:
+ (UIImage *)imageNamed:(NSString *)name
要注意的是這個方法適用於已經匯入到專案中的圖片。
其餘工廠方法:
+ (UIImage *)imageWithContentsOfFile:(NSString *)path // 透過檔案載入指定路徑下的內容獲得新圖片 + (UIImage *)imageWithData:(NSData *)data // 透過一個 NSData 物件獲得圖片 + (UIImage *)imageWithData:(NSData *)data scale:(CGFloat)scale // 同上,再加上圖片大小比例,用來改變圖片大小 + (UIImage *)imageWithCGImage:(CGImageRef)cgImage // 使用 Quartz 2D 物件建立 UIImage + (UIImage *)imageWithCGImage:(CGImageRef)imageRef scale:(CGFloat)scale orientation:(UIImageOrientation)orientation // 指定圖片的比例與方向,方向是個列舉型別 + (UIImage *)imageWithCIImage:(CIImage *)ciImage // 用一個 Core Image 物件建立圖像 + (UIImage *)imageWithCIImage:(CIImage *)ciImage scale:(CGFloat)scale orientation:(UIImageOrientation)orientation // 再加上比例與圖片方向 - (UIImage *)imageWithAlignmentRectInsets:(UIEdgeInsets)alignmentInsets // 返回指定矩形區域內的圖像 + (UIImage *)animatedImageNamed:(NSString *)name duration:(NSTimeInterval)duration // 建立動態圖片,持續時間為 duration + (UIImage *)animatedImageWithImages:(NSArray *)images duration:(NSTimeInterval)duration // 用一組圖片建立動態圖片,持續時間 duration + (UIImage *)animatedResizableImageNamed:(NSString *)name capInsets:(UIEdgeInsets)capInsets duration:(NSTimeInterval)duration // 建立可在變動大小圖片的指定矩形區域內播放的動態圖片 + (UIImage *)animatedResizableImageNamed:(NSString *)name capInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode duration:(NSTimeInterval)duration // 同上,多了一個圖片變化方式,具體來說就是平鋪或拉伸 - (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets // 用指定矩形區域建立圖像 - (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode // 同上,指定圖片變化方式
以下初始方法的用途都能在上面找到對應原型,這裡不再逐一註解:
– initWithContentsOfFile: // 從檔案載入圖片 – initWithData: // 用 NSData 物件初始化圖片 – initWithData:scale: // 用 NSData 物件與指定比例初始化圖片 – initWithCGImage: – initWithCGImage:scale:orientation: – initWithCIImage: – initWithCIImage:scale:orientation:
– drawAtPoint: // 在指定的點開始繪畫圖片,這個點就是圖片的左上角頂點 – drawAtPoint:blendMode:alpha: // 在指定的點繪製整個圖片,使用自訂圖片複合模式並設定透明度 – drawInRect: // 在指定區域內繪製圖片,可依需要縮放圖片 – drawInRect:blendMode:alpha: // 參照上面第二條 – drawAsPatternInRect: // 在指定區域內平鋪圖片
imageOrientation // 圖片的方向 size // 圖片的大小 scale // 圖片的比例 resizingMode // 圖片變化方式 CGImage // 潛在的 Quartz image CIImage // 潛在的 Core Image images // 返回一個由圖片組成的陣列,針對由一組圖片生成的動態圖片 duration // 返回動態圖片持續的時間(即播放一遍的時間) capInsets // 圖片上選定的區域 alignmentRectInsets // 圖片平鋪的區域