應用中有時咱們會有保存圖片的需求,如利用UIImagePickerController用IOS設備內置的相機拍照,或是有時咱們在應用程序中利用UIKit的 UIGraphicsBeginImageContext,UIGraphicsEndImageContext,UIGraphicsGetImageFromCurrentImageContext方法建立一張圖像須要進行保存。 IOS的UIKit Framework提供了UIImageWriteToSavedPhotosAlbum方法對圖像進行保存,該方法會將image保存至用戶的相冊中,描述以下: 異步
1spa |
void UIImageWriteToSavedPhotosAlbum (對象 |
2圖片 |
UIImage *image,ci |
3get |
id completionTarget,it |
4io |
SEL completionSelector,table |
5class |
void *contextInfo |
6 |
); |
參數說明:
image
帶保存的圖片UImage對象
completionTarget
圖像保存至相冊後調用completionTarget指定的selector(可選)
completionSelector
completionTarget的方法對應的選擇器,至關於回調方法,需知足如下格式
1 |
- (void) image: (UIImage *) image |
2 |
didFinishSavingWithError: (NSError *) error |
3 |
contextInfo: (void *) contextInfo; |
contextInfo指定了在回調中可選擇傳入的數據。
當咱們須要異步得到圖像保存結果的消息時,咱們須要指定completionTarget對象以及其completionSelector對應的選擇器。示例以下:
01 |
- (void)saveImageToPhotos:(UIImage*)savedImage |
02 |
{ |
03 |
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL); |
04 |
} |
05 |
// 指定回調方法 |
06 |
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo |
07 |
{ |
08 |
NSString *msg = nil ; |
09 |
if(error != NULL){ |
10 |
msg = @"保存圖片失敗" ; |
11 |
}else{ |
12 |
msg = @"保存圖片成功" ; |
13 |
} |
14 |
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存圖片結果提示" |
15 |
message:msg |
16 |
delegate:self |
17 |
cancelButtonTitle:@"肯定" |
18 |
otherButtonTitles:nil]; |
19 |
[alert show]; |
20 |
} |
21 |
|
22 |
// 調用示例 |
23 |
UIImage *savedImage = [UIImage imageNamed:"savedImage.png"]; |
24 |
|
25 |
[self saveImageToPhotos:savedImage]; |