2014-10-04 91 views
1

我有一个显示在UICollectionView中的图像数组。保存在UIImageView中显示的图像

当集合视图中的单元格被按下时,该图像被推送到视图控制器并显示在UIImageView中。

我想然后能够按下按钮并将图像保存到用户相机胶卷。

但我有一些麻烦,这样做...

我觉得我在右边行的代码,但不能把一切共同努力:

- (IBAction)onClickSavePhoto:(id)sender{ 

    UIImage *img = [UIImage imageNamed:@"which ever image is being currently displayed in the image view"]; 

    UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil); 
} 

我如何操作代码以允许用户保存图像视图中显示的图像?

在此先感谢!

UPDATE:

发现在另一篇文章中解决问题的办法:

Save image in UIImageView to iPad Photos Library

回答

1

如何将图像保存到库:

您可以使用此功能:

UIImageWriteToSavedPhotosAlbum(UIImage *image, 
           id completionTarget, 
           SEL completionSelector, 
           void *contextInfo); 

你只需要completionTargetcompletionSelectorcontextInfo如果你希望在UIImage储存完成后通知,否则,你可以在nil通过。

More info here

据说更快的方法,将图像保存到库比使用UIImageWriteToSavedPhotosAlbum: 可以去看更加快速然后UIImageWriteToSavedPhotosAlbum的方式来使用的是iOS 4.0+ AVFoundation框架

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; 
    [library writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)[image imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){ 
    if (error) { // TODO: error handling } 
    else { // TODO: success handling } 
}]; 

//for non-arc projects 
//[library release]; 

以UIImageView的形式获取图像作为屏幕截图:

iOS 7有一个新的方法,允许您在当前图形上下文中绘制视图层次结构。这可以用来快速获取UIImage。

这是上的UIView一个类中的方法来获得该视图为的UIImage:

- (UIImage *)takeSnapShot { 
    UIGraphicsBeginImageContextWithOptions(self.myImageView.bounds.size, NO, [UIScreen mainScreen].scale); 

    [self drawViewHierarchyInRect:self.myImageView.bounds afterScreenUpdates:YES]; 

    // old style [self.layer renderInContext:UIGraphicsGetCurrentContext()]; 

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    return image; 
} 

它是相当快则现有renderInContext:方法。

参考:https://developer.apple.com/library/ios/qa/qa1817/_index.html

更新SWIFT:一个扩展,不一样的:

extension UIView { 

    func takeSnapshot() -> UIImage { 
     UIGraphicsBeginImageContextWithOptions(self.myImageView.bounds.size, false, UIScreen.mainScreen().scale); 

     self.drawViewHierarchyInRect(self.myImageView.bounds, afterScreenUpdates: true) 

     // old style: self.layer.renderInContext(UIGraphicsGetCurrentContext()) 

     let image = UIGraphicsGetImageFromCurrentImageContext(); 
     UIGraphicsEndImageContext(); 
     return image; 
    } 
} 
相关问题