ios 捕获 UIView 并另存为图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17145049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:57:54  来源:igfitidea点击:

Capture UIView and Save as Image

iosobjective-cios6swift3

提问by Rushabh

First of i Add the UILableon UIImageViewand then after i screenshot the UIView, the image not proper capture the UIViewFrame i also attach the image url.

首先,我的添加UILableUIImageView,然后后,我截图UIView,图像不正确的捕捉UIView帧我还附上了图片的URL。

enter image description here

在此处输入图片说明

1) Original Image Link:

1) 原图链接:

enter image description here

在此处输入图片说明

2) After Capture the image Link:

2)捕获图像链接后:

Code:

代码:

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];

回答by Paras Joshi

You can take the screenshots of any UIViewor capture any UIViewand save it as an image with below code.

您可以使用以下代码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;

}

回答by Jawad Zeb

Take snapshot of a UIView

拍摄 UIView 的快照

pass your view to this function it will handle everything itself( No need to set bounds or frames)

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

- (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;
}

回答by Marckaraujo

Swift 3 Version:

斯威夫特 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
}

回答by Sonu

you can use the below code to

您可以使用以下代码

UIGraphicsBeginImageContext(pictureView.bounds.size); ?                    
[pictureView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);

回答by Venk

Try like this,

试试这样,

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];

回答by Mehsam Saeed

Try this if you want captured image maintain its original quality.

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

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

回答by Olcay Erta?

In Swift 5 as extension:

在 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({
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?()
}
.isKeyWindow}).first?.rootViewController else { return } controller.present(self, animated: true) } }

In your UIViewsub class:

在您的UIView子类中:

##代码##