一尘不染

如何截取部分UIView的屏幕截图?

swift

我希望用户在Swift中以编程方式按下按钮后继续运行我的应用并为应用截图。我知道UIGraphicsGetImageFromCurrentImageContext()需要截图,但是我不需要整个屏幕的图片。我希望弹出一个矩形(有点像裁剪工具),并且用户可以拖动矩形并调整其大小以仅截取屏幕的特定部分的屏幕截图。我希望矩形经过a
WKWebView并裁剪Web视图的图片。


阅读 436

收藏
2020-07-07

共1个答案

一尘不染

标准的快照技术是drawHierarchy(in:afterScreenUpdates:),将其绘制到图像上下文。在iOS
10及更高版本中,您可以使用UIGraphicsImageRenderer

extension UIView {

    /// Create image snapshot of view.
    ///
    /// - Parameters:
    ///   - rect: The coordinates (in the view's own coordinate space) to be captured. If omitted, the entire `bounds` will be captured.
    ///   - afterScreenUpdates: A Boolean value that indicates whether the snapshot should be rendered after recent changes have been incorporated. Specify the value false if you want to render a snapshot in the view hierarchy’s current state, which might not include recent changes. Defaults to `true`.
    ///
    /// - Returns: The `UIImage` snapshot.

    func snapshot(of rect: CGRect? = nil, afterScreenUpdates: Bool = true) -> UIImage {
        return UIGraphicsImageRenderer(bounds: rect ?? bounds).image { _ in
            drawHierarchy(in: bounds, afterScreenUpdates: afterScreenUpdates)
        }
    }
}

而且您会这样使用:

let image = webView.snapshot(of: rect)

在iOS 10之前,您需要获取图像的一部分,可以使用CGImagemethod
cropping(to:)。例如:

extension UIView {

    /// Create snapshot
    ///
    /// - Parameters:
    ///   - rect: The coordinates (in the view's own coordinate space) to be captured. If omitted, the entire `bounds` will be captured.
    ///   - afterScreenUpdates: A Boolean value that indicates whether the snapshot should be rendered after recent changes have been incorporated. Specify the value false if you want to render a snapshot in the view hierarchy’s current state, which might not include recent changes. Defaults to `true`.
    ///
    /// - Returns: Returns `UIImage` of the specified portion of the view.

    func snapshot(of rect: CGRect? = nil, afterScreenUpdates: Bool = true) -> UIImage? {
        // snapshot entire view

        UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
        drawHierarchy(in: bounds, afterScreenUpdates: afterScreenUpdates)
        let wholeImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        // if no `rect` provided, return image of whole view

        guard let image = wholeImage, let rect = rect else { return wholeImage }

        // otherwise, grab specified `rect` of image

        guard let cgImage = image.cgImage?.cropping(to: rect * image.scale) else { return nil }
        return UIImage(cgImage: cgImage, scale: image.scale, orientation: .up)
    }

}

使用以下便利操作符:

extension CGRect {
    static func * (lhs: CGRect, rhs: CGFloat) -> CGRect {
        return CGRect(x: lhs.minX * rhs, y: lhs.minY * rhs, width: lhs.width * rhs, height: lhs.height * rhs)
    }
}

并使用它,您可以执行以下操作:

if let image = webView.snapshot(of: rect) {
    // do something with `image` here
}

2020-07-07