如何将图像保存到库中:
你可以使用这个功能:
UIImageWriteToSavedPhotosAlbum(UIImage *image,
id completionTarget,
SEL completionSelector,
void *contextInfo);
你只需要completionTarget、completionSelector和contextInfo,如果你想在UIImage完成保存时得到通知,否则你可以传入nil。
More info here
可能比使用 UIImageWriteToSavedPhotosAlbum 更快地将图像保存到库中:
使用 iOS 4.0+ AVFoundation 框架的方式比 UIImageWriteToSavedPhotosAlbum 快得多
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;
}
}