将图片保存在iPhone的相册中

来源:互联网 发布:软件测试行业方向 编辑:程序博客网 时间:2024/04/26 03:26

原文地址:http://blog.csdn.net/microchenhong/article/details/6524960

有时候你的应用需要将应用中的图片保存到用户iPhone或者iTouch的相册中。 可以使用UIKit的这个类方法来完成。

[cpp] view plaincopy
  1. void UIImageWriteToSavedPhotosAlbum (  
  2.    UIImage  *image,  
  3.    id       completionTarget,  
  4.    SEL      completionSelector,  
  5.    void     *contextInfo  
  6. );  

 

image
要保存到用户设备中的图片

completionTarget
当保存完成后,回调方法所在的对象

completionSelector
当保存完成后,所调用的回调方法。 形式如下:

( void ) image: ( UIImage *) image
    didFinishSavingWithError: ( NSError *) error
    contextInfo: ( void *) contextInfo;
 

contextInfo
可选的参数,保存了一个指向context数据的指针,它将传递给回调方法。

比如你可以这样来写一个存贮照片的方法:

// 要保存的图片 
  UIImage *img = [ UIImage imageNamed:@"ImageName.png" ] ;   
 
  // 保存图片到相册中 
  UIImageWriteToSavedPhotosAlbum( img, self, @selector (image:didFinishSavingWithError:contextInfo:) , nil ) ; 
 

回调方法看起来可能是这样:

[cpp] view plaincopy
  1. - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error  
  2.              contextInfo:(void *)contextInfo  
  3.   {  
  4.     // Was there an error?  
  5.     if (error != NULL)  
  6.     {  
  7.       // Show error message…  
  8.    
  9.     }  
  10.     else  // No errors  
  11.     {  
  12.       // Show message image successfully saved  
  13.     }  
  14.   }  


保存当前视图:

#import  <QuartzCore/QuartzCore.h>

UIGraphicsBeginImageContext(currentView.bounds .size ); //currentView 当前的 view

[currentView. layer  renderInContext: UIGraphicsGetCurrentContext()];

UIImage *viewImage =  UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

UIImageWriteToSavedPhotosAlbum(viewImage, nil , nil , nil );