如何以编程方式使用 UIGraphicsImageRenderer 获取高质量屏幕截图?

Par*_*lim 7 uiimage cgcontext ios swift uigraphicsimagerenderer

问题:截取屏幕截图后,通过缩放检查时图像模糊。缩放时图像内的文字似乎变得模糊。

我知道这个问题已经被多次提出,但没有一个人想要得到解决。我已经检查了很多像这样的帖子

到目前为止,该论坛上共享的所有解决方案都是重复的或以任何其他方式相同,但没有一个解决方案可以解决该问题。

这是我正在做的事情:

extension UIView {

  func asImage() -> UIImage? {
    let format = UIGraphicsImageRendererFormat()
    format.opaque = self.isOpaque
    let renderer = UIGraphicsImageRenderer(bounds: bounds,format: format)
    return renderer.image(actions: { rendererContext in
        layer.render(in: rendererContext.cgContext)
    })
}

//The other option using UIGraphicsEndImageContext

func asImage() -> UIImage? {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0.0)
    defer { UIGraphicsEndImageContext() }
    if let context = UIGraphicsGetCurrentContext() {
        self.layer.render(in: context)
        return UIGraphicsGetImageFromCurrentImageContext()
    }
    return nil
}
}
Run Code Online (Sandbox Code Playgroud)

上面的函数将UIView转换为图像,但是返回的图像质量不合格。

waz*_*ski 0

Update: Reported this solution is not longer useful from iOS17 and above.

我在我的一个应用程序中使用此代码,并且似乎工作正常。不知道它的品质是否适合你。

import UIKit

extension UIApplication {

    var screenShot: UIImage?  {

        if let layer = keyWindow?.layer {
            let scale = UIScreen.main.scale

            UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);
            if let context = UIGraphicsGetCurrentContext() {
                layer.render(in: context)
                let screenshot = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext()
                return screenshot
            }
        }
        return nil
    }
}
Run Code Online (Sandbox Code Playgroud)