ios - 根据 UIImage 大小捕获屏幕

标签 ios iphone swift xcode uiimage

我在捕获自定义 View 时遇到问题。我正在尝试将捕获的图像设置为 UIImage 图像数据的大小,但是当我截取屏幕截图时,图像是这样的! :

enter image description here

图像缩小了! 这是代码:

  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

但是图像会失真:

enter image description here

最佳答案

我尝试使用以下方法使用 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),这是图像的原始大小。

enter image description here

关于ios - 根据 UIImage 大小捕获屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44931810/

相关文章:

iphone - 游戏中心问题

ios - 找出 swift 协议(protocol)的所有实现者的名字

iOS 使用 Core Motion 计算设备速度

objective-c - swift init 在 objective-C 中不可见

ios - 在ios7中拍摄状态栏快照

ios - 界面生成器中的 CATextLayer?

ios - 有什么办法可以在应用程序商店外分发 ios 应用程序?

ios - swift 将 var 从一个 if 语句传递到另一个

iphone - 使用 Core Data 时如何覆盖属性上的 getter?

iphone - 模型、 View 、 Controller 混淆