捕获UIView并另存为图像

时间:2013-06-17 10:11:21

标签: ios objective-c ios6 swift3

首先我在UILable上添加UIImageView,然后在我截取UIView之后,图片不正确地捕获UIView帧我也附加了图片网址。

enter image description here

1) Original Image Link:

enter image description here

2) After Capture the image Link:

代码:

UIGraphicsBeginImageContext(viewImage.frame.size);
[viewImage.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *vwImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

NSData *data=UIImagePNGRepresentation(vwImage);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// NSString *imgName = [NSString stringWithFormat:imagename];
NSString *strPath = [documentsDirectory stringByAppendingPathComponent:imagename];
[data writeToFile:strPath atomically:YES];

7 个答案:

答案 0 :(得分:25)

您可以截取任何UIView的屏幕截图或捕获任何UIView,并将其保存为包含以下代码的图片。

- (UIImage *)captureView {

    //hide controls if needed
    CGRect rect = [self.view bounds];

    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [self.view.layer renderInContext:context];   
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;

}

答案 1 :(得分:13)

拍摄UIView的快照

将您的视图传递给此函数,它将自行处理所有内容(无需设置边界或框架

- (UIImage *)takeSnapshotOfView:(UIView *)view
{
    UIGraphicsBeginImageContext(CGSizeMake(view.frame.size.width, view.frame.size.height));
    [view drawViewHierarchyInRect:CGRectMake(0, 0, view.frame.size.width, view.frame.size.height) afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

答案 2 :(得分:9)

Swift 3版本:

func takeSnapshotOfView(view:UIView) -> UIImage? {
        UIGraphicsBeginImageContext(CGSize(width: view.frame.size.width, height: view.frame.size.height))
        view.drawHierarchy(in: CGRect(x: 0.0, y: 0.0, width: view.frame.size.width, height: view.frame.size.height), afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }

答案 3 :(得分:2)

您可以使用以下代码

UIGraphicsBeginImageContext(pictureView.bounds.size); 
                    

[pictureView.layer renderInContext:UIGraphicsGetCurrentContext()]; 

UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);

答案 4 :(得分:1)

在Swift 5中作为扩展名:

extension UIView {

    func takeSnapshot() -> UIImage? {
        UIGraphicsBeginImageContext(CGSize(width: self.frame.size.width, height: self.frame.size.height - 5))
        let rect = CGRect(x: 0.0, y: 0.0, width: self.frame.size.width, height: self.frame.size.height)
        drawHierarchy(in: rect, afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

extension UIImage {

    func saveToPhotoLibrary(_ completionTarget: Any?, _ completionSelector: Selector?) {
        DispatchQueue.global(qos: .userInitiated).async {
            UIImageWriteToSavedPhotosAlbum(self, completionTarget, completionSelector, nil)
        }
    }
}

extension UIAlertController {

    func present() {
        guard let controller = UIApplication.shared.windows.filter({$0.isKeyWindow}).first?.rootViewController else {
            return
        }
        controller.present(self, animated: true)
    }
}

在您的UIView子类中:

func saveImage() {
    let selector = #selector(self.onImageSaved(_:error:contextInfo:))
    takeSnapshot()?.saveToPhotoLibrary(self, selector)
}

@objc private func onImageSaved(_ image: UIImage, error: Error?, contextInfo: UnsafeRawPointer) {
    if let error = error {
        let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        ac.present()
    } else {
        let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        ac.present()
    }
    onImageSaved?()
}

答案 5 :(得分:0)

试试这个,

UIGraphicsBeginImageContext(viewImage.frame.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[[UIColor blackColor] set];
CGContextFillRect(ctx, viewImage.frame);     

[viewImage.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *vwImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

NSData *data=UIImagePNGRepresentation(vwImage);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// NSString *imgName = [NSString stringWithFormat:imagename];
NSString *strPath = [documentsDirectory stringByAppendingPathComponent:imagename];
[data writeToFile:strPath atomically:YES];

答案 6 :(得分:0)

如果要使捕获的图像保持其原始质量,请尝试此操作。

-(UIImage*)captureViewWithAllSubView:(UIView*)view{
   UIGraphicsBeginImageContextWithOptions(view.bounds.size, 
   view.opaque, 0.0f);
   [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
   UIImage *capturedImage = 
   UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();
   return capturedImage;}