【问题标题】:How to take high-quality screenshot with UIGraphicsImageRenderer programmatically?如何以编程方式使用 UIGraphicsImageRenderer 获取高质量的屏幕截图?
【发布时间】:2026-02-22 23:15:01
【问题描述】:

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

我知道这个问题已经被提出过很多次了,但他们都没有想要的解决方案。我已经查了很多帖子,比如this one

到目前为止,在本论坛上分享的所有解决方案都以任何其他方式重复或相同,但没有一个解决方案。

这是我正在做的事情:

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
}
}

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

【问题讨论】:

  • 你到底想用你的代码做什么?你截图?如何?而你只是想调整它的大小?原图在哪里?
  • 请检查我更新的问题。我正在尝试截屏,或者您可以说将 UIView 转换为图像。但是返回的图像质量不好。
  • 这不是问题的根源。
  • 我现在知道你想做什么了。不,您只能获得屏幕截图的视图大小。如果将其调整为更大的尺寸,当然,生成的图片会变得模糊。
  • 不,即使我不调整它的大小,如果不根据实际边界调整它的大小,它也会变得模糊。这就是我遇到的问题。我的意思是当你正常看时它看起来很完美,但是当你放大它时,像素不足以提供清晰的视觉效果。

标签: ios swift uiimage cgcontext uigraphicsimagerenderer


【解决方案1】:

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

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
    }
}

【讨论】:

  • 这看起来像您使用手机屏幕的大小。所以我猜当你导出这个截图并放大它时,你会得到模糊的图像。
  • 是的,我使用的是屏幕大小,因为我在同一个屏幕上渲染图像,但是您可以将比例调整到您想要的大小。我没有看到模糊效果,但我会检查一下。
【解决方案2】:

我使用此扩展从视图中创建图像 UIGraphicsGetCurrentContext() 返回对当前图形上下文的引用。它不会创建一个。记住这一点很重要,因为如果你这样看,你会发现它不需要 size 参数,因为当前上下文只是创建图形上下文时使用的大小。

extension UIView {
   func toImage() -> UIImage? {
      UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)

      drawHierarchy(in: self.bounds, afterScreenUpdates: true)

      let image = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext()

      return image
   }
}

【讨论】:

  • 我已经尝试过了,正如您在我的问题中看到的那样。问题是它需要对可见区域进行屏幕截图,因此当您对其进行缩放时,文本和图像的像素会变得模糊。这是不可接受的。
【解决方案3】:

执行UIView“图像捕获”不会获得您想要的结果。

当您缩放UIScrollView 时,它执行矢量缩放...它执行光栅化缩放。

您可以使用UILabel 作为viewForZooming 轻松确认这一点。这是一个带有 30 点系统字体的标签...

1x 放大:

10x 放大:

该示例的代码:

class ViewController: UIViewController, UIScrollViewDelegate {
    
    let zoomLabel: UILabel = UILabel()
    let scrollView: UIScrollView = UIScrollView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        [zoomLabel, scrollView].forEach {
            $0.translatesAutoresizingMaskIntoConstraints = false
        }
        
        scrollView.addSubview(zoomLabel)
        view.addSubview(scrollView)
        
        let g = view.safeAreaLayoutGuide
        
        NSLayoutConstraint.activate([
            
            scrollView.centerXAnchor.constraint(equalTo: g.centerXAnchor),
            scrollView.centerYAnchor.constraint(equalTo: g.centerYAnchor),
            scrollView.widthAnchor.constraint(equalToConstant: 300.0),
            scrollView.heightAnchor.constraint(equalToConstant: 200.0),
            
            zoomLabel.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor),
            zoomLabel.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor),
            zoomLabel.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor),
            zoomLabel.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor),
            
        ])
        
        zoomLabel.textColor = .red
        zoomLabel.backgroundColor = .yellow
        zoomLabel.font = UIFont.systemFont(ofSize: 30.0, weight: .regular)
        zoomLabel.text = "Sample Text"
        
        scrollView.delegate = self
        scrollView.minimumZoomScale = 1
        scrollView.maximumZoomScale = 10
        
        view.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        scrollView.backgroundColor = .white
    }
    

    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return zoomLabel
    }

}

当您将视图内容“捕获”为UIImage 时,您会得到一个位图,该位图是视图的大小以点为单位 x 屏幕比例。

因此,例如,在 iPhone 8 上,屏幕比例为 @2x300 x 200 处的视图将被“捕获”为具有 600 x 400 像素的 UIImage

无论是缩放视图本身,还是对视图进行位图捕获,都会得到相同的结果——缩放时边缘模糊。

您的 cmets 包括:"...在编辑图像时..." -- 这是一个常见问题,我们希望允许用户添加文本(标签)、贝塞尔路径形状,添加图像等。例如,用户在屏幕上看到的可能是3000 x 2000像素的原始图像,显示在300 x 200点处。添加一个 30 点的标签在屏幕上可能看起来不错,但随后将其作为UIImage(用于缩放或保存到磁盘)最终成为600 x 400 像素图像,当然,在更大的尺寸上不会很好看。

通常,解决此问题的方法如下:

允许用户在屏幕尺寸进行编辑,例如

  • 300 x 200 视图中显示按比例缩小的3000 x 2000 像素图像
  • 添加一个 Bezier 路径,椭圆直角(20、20、200、200)
  • 在原点(32, 32)添加一个30点标签

然后,当“捕获”输出/缩放时

  • 获取原图3000 x 2000像素图片
  • 添加一个贝塞尔路径,椭圆形矩形(20 * 10, 20 * 10, 200 * 10, 200 * 10)
  • 在原点(32 * 10, 32 * 10)添加一个(30 * 10)点标签

另一种选择是进行屏幕编辑缩小

因此,您可以使用300 x 200 图像视图和3000 x 2000 像素图像(缩放以适应)。当用户说“我想在 rect (20, 20, 200, 200) 中添加一个椭圆形 Bezier 路径时,您的代码将在图像本身的 rect (20 * 10, 20 * 10, 200 * 10, 200 * 10) 处绘制该椭圆形,然后刷新 .image 的属性图像视图。

这里有一个更详细的例子来帮助说明问题:

class ViewController: UIViewController, UIScrollViewDelegate {
    
    let topView: UIView = UIView()
    let topLabel: UILabel = UILabel()
    
    let botView: UIView = UIView()
    let botLabel: UILabel = UILabel()
    
    let topScrollView: UIScrollView = UIScrollView()
    let botScrollView: UIScrollView = UIScrollView()

    let topStatLabel: UILabel = UILabel()
    let botStatLabel: UILabel = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        [topView, topLabel, botView, botLabel, topScrollView, botScrollView, topStatLabel, botStatLabel].forEach {
            $0.translatesAutoresizingMaskIntoConstraints = false
        }
        
        topView.addSubview(topLabel)
        botView.addSubview(botLabel)

        topScrollView.addSubview(topView)
        botScrollView.addSubview(botView)

        view.addSubview(topStatLabel)
        view.addSubview(botStatLabel)
        
        view.addSubview(topScrollView)
        view.addSubview(botScrollView)
        
        let g = view.safeAreaLayoutGuide
        
        NSLayoutConstraint.activate([
            
            topStatLabel.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
            topStatLabel.leadingAnchor.constraint(equalTo: topScrollView.leadingAnchor),

            topScrollView.topAnchor.constraint(equalTo: topStatLabel.bottomAnchor, constant: 4.0),
            topScrollView.centerXAnchor.constraint(equalTo: g.centerXAnchor),
            topScrollView.widthAnchor.constraint(equalToConstant: 300.0),
            topScrollView.heightAnchor.constraint(equalToConstant: 200.0),
            
            botScrollView.topAnchor.constraint(equalTo: topScrollView.bottomAnchor, constant: 12.0),
            botScrollView.centerXAnchor.constraint(equalTo: g.centerXAnchor),
            botScrollView.widthAnchor.constraint(equalToConstant: 300.0),
            botScrollView.heightAnchor.constraint(equalToConstant: 200.0),
            
            botStatLabel.topAnchor.constraint(equalTo: botScrollView.bottomAnchor, constant: 4.0),
            botStatLabel.leadingAnchor.constraint(equalTo: botScrollView.leadingAnchor),
            
            topView.widthAnchor.constraint(equalToConstant: 300.0),
            topView.heightAnchor.constraint(equalToConstant: 200.0),
            
            botView.widthAnchor.constraint(equalToConstant: 300.0 * 10.0),
            botView.heightAnchor.constraint(equalToConstant: 200.0 * 10.0),
            
            topLabel.topAnchor.constraint(equalTo: topView.topAnchor, constant: 8.0),
            topLabel.leadingAnchor.constraint(equalTo: topView.leadingAnchor, constant: 8.0),

            botLabel.topAnchor.constraint(equalTo: botView.topAnchor, constant: 8.0 * 10.0),
            botLabel.leadingAnchor.constraint(equalTo: botView.leadingAnchor, constant: 8.0 * 10.0),
            
            topView.topAnchor.constraint(equalTo: topScrollView.contentLayoutGuide.topAnchor),
            topView.leadingAnchor.constraint(equalTo: topScrollView.contentLayoutGuide.leadingAnchor),
            topView.trailingAnchor.constraint(equalTo: topScrollView.contentLayoutGuide.trailingAnchor),
            topView.bottomAnchor.constraint(equalTo: topScrollView.contentLayoutGuide.bottomAnchor),

            botView.topAnchor.constraint(equalTo: botScrollView.contentLayoutGuide.topAnchor),
            botView.leadingAnchor.constraint(equalTo: botScrollView.contentLayoutGuide.leadingAnchor),
            botView.trailingAnchor.constraint(equalTo: botScrollView.contentLayoutGuide.trailingAnchor),
            botView.bottomAnchor.constraint(equalTo: botScrollView.contentLayoutGuide.bottomAnchor),
            
        ])
        
        topLabel.textColor = .red
        topLabel.backgroundColor = .yellow
        topLabel.font = UIFont.systemFont(ofSize: 30.0, weight: .regular)
        topLabel.text = "Sample Text"
        
        botLabel.textColor = .red
        botLabel.backgroundColor = .yellow
        botLabel.font = UIFont.systemFont(ofSize: 30.0 * 10.0, weight: .regular)
        botLabel.text = "Sample Text"
        
        topScrollView.delegate = self
        topScrollView.minimumZoomScale = 1
        topScrollView.maximumZoomScale = 10
        
        botScrollView.delegate = self
        botScrollView.minimumZoomScale = 0.1
        botScrollView.maximumZoomScale = 1
        
        topScrollView.zoomScale = topScrollView.minimumZoomScale
        botScrollView.zoomScale = botScrollView.minimumZoomScale

        view.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        topScrollView.backgroundColor = .white
        botScrollView.backgroundColor = .white

        topStatLabel.font = UIFont.systemFont(ofSize: 14, weight: .light)
        topStatLabel.numberOfLines = 0
        botStatLabel.font = UIFont.systemFont(ofSize: 14, weight: .light)
        botStatLabel.numberOfLines = 0
        
        let t = UITapGestureRecognizer(target: self, action: #selector(self.tapped(_:)))
        view.addGestureRecognizer(t)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        updateStatLabels()
    }
    
    func updateStatLabels() -> Void {
        var sTop = ""
        sTop += "Label Point Size: \(topLabel.font.pointSize)"
        sTop += "\n"
        sTop += "Label Frame: \(topLabel.frame)"
        sTop += "\n"
        sTop += "View Size: \(topView.bounds.size)"
        sTop += "\n"
        sTop += "Zoom Scale: \(String(format: "%0.1f", topScrollView.zoomScale))"
        
        var sBot = ""
        sBot += "Zoom Scale: \(String(format: "%0.1f", botScrollView.zoomScale))"
        sBot += "\n"
        sBot += "View Size: \(botView.bounds.size)"
        sBot += "\n"
        sBot += "Label Frame: \(botLabel.frame)"
        sBot += "\n"
        sBot += "Label Point Size: \(botLabel.font.pointSize)"
        
        topStatLabel.text = sTop
        botStatLabel.text = sBot
    }
    
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        if scrollView == topScrollView {
            return topView
        }
        return botView
    }
    
    @objc func tapped(_ g: UITapGestureRecognizer) -> Void {
        
        if Int(topScrollView.zoomScale) == Int(topScrollView.maximumZoomScale) {
            topScrollView.zoomScale = topScrollView.minimumZoomScale
        } else {
            topScrollView.zoomScale += 1
        }
        topScrollView.contentOffset = .zero

        // comparing floating point directly will fail, so round the values
        if round(botScrollView.zoomScale * 10) == round(botScrollView.maximumZoomScale * 10) {
            botScrollView.zoomScale = botScrollView.minimumZoomScale
        } else {
            botScrollView.zoomScale += 0.1
        }

        botScrollView.contentOffset = .zero

        updateStatLabels()
    }
    
}

顶部滚动视图有一个带有 30 磅标签的 300 x 200 视图,允许从 1 to 10 缩放缩放。

底部滚动视图有一个带有 300 点标签的 3000 x 2000 视图,允许从 0.1 to 1.0 缩放缩放。

每次点击屏幕时,scrollViews 将 zoomScale 分别增加 1 和 0.1。

在最小比例下看起来像这样:

在 5 和 0.5 级:

10 和 1.0 比例:

【讨论】:

  • 感谢您的描述性回答。那意义重大。但是在我的应用程序中,我正在使用图像编辑器,并且我不打算向用户显示缩放的画布,我只有固定边界,它是屏幕绑定大小。并且用户将只能在该范围内添加内容。所以我唯一的选择是创建现有编辑器视图的副本并根据所需的图像大小比重新创建内容。