基于UIImage大小捕获屏幕

我有捕获自定义视图的问题。 我正在设置大小UIImage图像数据的大小捕获的图像,但是当我把截图的图像是这样的! :

在这里输入图像说明

图像缩小! 这里是代码:

  UIGraphicsBeginImageContextWithOptions((self.photoImage.size), false, UIScreen.main.scale) self.captureView.layer.render(in: UIGraphicsGetCurrentContext()!) self.photoToShare = UIGraphicsGetImageFromCurrentImageContext() print(self.photoToShare.size) //the size is right UIGraphicsEndImageContext() self.photo.image = self.photoToShare! 

问题是什么 ?!

我累了: self.captureView.drawHierarchy(in: self.captureView.bounds , afterScreenUpdates: true)

仍然没有成功

编辑

我尝试了这种方法,抓住然后裁剪,但仍然没有成功

 UIGraphicsBeginImageContextWithOptions(self.captureView.bounds.size, false, UIScreen.main.scale) self.captureView.drawHierarchy(in: self.captureView.bounds, afterScreenUpdates: true) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let cropRect = CGRect(x: 0, y: 0, width: (self.photoImage.size.width) , height: (self.photoImage.size.height)) UIGraphicsBeginImageContextWithOptions(cropRect.size, false, UIScreen.main.scale) image?.draw(in: cropRect) let finalImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.photo.image = finalImage 

但是图像会被扭曲:

在这里输入图像说明

我已经尝试捕获aspectviewFit内容模式的图像视图的屏幕截图和具有以下方法没有恒定的宽度和高度

 func captureShot() { let layer : CALayer = self.imageView!.layer UIGraphicsBeginImageContextWithOptions((layer.frame.size), false, 1.0); layer.render(in: UIGraphicsGetCurrentContext()!) let screenshot = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() } 

&返回截图有相同的图像大小(229 * 220),这是图像的原始大小。

在这里输入图像说明

尝试这个:

 extension UIView { var screenCapture: UIImage { UIGraphicsBeginImageContextWithOptions(bounds.size, opaque, 0.0) drawViewHierarchyInRect(bounds, afterScreenUpdates: true) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } } 

把它放在一个UImageView中:

 let imageView = UIImageView() imageView.contentMode = .scaleAspectFit imageView.image = someView.screenCapture imageView.frame = someFrame someSuperview.addSubview(imageView) 

(抱歉,所有的some ,但希望它不是混乱:)

希望这可以帮助!