捕获UIView并保存为图像

首先在UIImageView上添加UILable ,然后在截图UIView ,图像不正确的捕获UIView帧,我也附加图像的URL。

在这里输入图像说明

1)原始图片链接: –

在这里输入图像说明

2)捕获图像链接后: –

代码: –

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

你可以截取任何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; } 

拍摄一个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; } 

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 } 

你可以使用下面的代码来

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

像这样尝试,

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