應(yīng)用中有時我們會有保存圖片的需求在扰,如利用UIImagePickerController用IOS設(shè)備內(nèi)置的相機拍照橙依,或是有時我們在應(yīng)用程序中利用UIKit的 UIGraphicsBeginImageContext顿天,UIGraphicsEndImageContext犀忱,UIGraphicsGetImageFromCurrentImageContext方法創(chuàng)建一張圖像需要進(jìn)行保存拣展。 IOS的UIKit Framework提供了UIImageWriteToSavedPhotosAlbum方法對圖像進(jìn)行保存坡垫,該方法會將image保存至用戶的相冊中梭灿,描述如下:
1
void UIImageWriteToSavedPhotosAlbum (
2
UIImage? *image,
3
id? ? ? completionTarget,
4
SEL? ? ? completionSelector,
5
void? ? *contextInfo
6
);參數(shù)說明:
image
帶保存的圖片UImage對象
completionTarget
圖像保存至相冊后調(diào)用completionTarget指定的selector(可選)
completionSelector
completionTarget的方法對應(yīng)的選擇器,相當(dāng)于回調(diào)方法冰悠,需滿足以下格式
- (void) image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo; ? ? ? ?contextInfo指定了在回調(diào)中可選擇傳入的數(shù)據(jù)堡妒。
當(dāng)我們需要異步獲得圖像保存結(jié)果的消息時,我們需要指定completionTarget對象以及其completionSelector對應(yīng)的選擇器溉卓。示例如下:
- (void)saveImageToPhotos:(UIImage*)savedImage
{
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}
// 指定回調(diào)方法
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo{
NSString *msg = nil ;
if(error != NULL){
msg = @"保存圖片失敗" ;
}else{
msg = @"保存圖片成功" ;
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存圖片結(jié)果提示"
message:msg delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil];
[alert show];
}
// 調(diào)用示例
UIImage *savedImage = [UIImage imageNamed:"savedImage.png"];
[self saveImageToPhotos:savedImage];