[英]How to resize a UIImageView based on UIImage size and fit the screen's width
[英]Capture screen based on UIImage size
我在捕获自定义视图时遇到问题。 我正在尝试将捕获的图像设置为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
但是图像会失真:
我试图用AspectToFit内容模式捕获imageview的屏幕截图,并且使用下面的方法没有固定的宽度和高度
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
S,但希望这不是混淆:)
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.