ios – 如何截取UIView的部分截图?

我希望用户在我的应用程序中使用 Swift中的编程按钮按下应用程序的屏幕截图.我知道UIGraphicsGetImageFromCurrentImageContext()需要截图,但我不想要整个屏幕的图片.我希望弹出一个矩形(有点像裁剪工具),用户可以拖动矩形并调整其大小,只截取屏幕的某个部分.我希望矩形遍历WKWebView并裁剪网页视图的图片.

解决方法

标准快照技术是drawViewHierarchyInRect.要获取图像的一部分,可以使用CGImageCreateWithImageInRect.

因此,在Swift 2中:

extension UIView {

    /// Create snapshot
    ///
    /// - parameter rect: The `CGRect` of the portion of the view to return. If `nil` (or omitted),///                   return snapshot of the whole view.
    ///
    /// - returns: Returns `UIImage` of the specified portion of the view.

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

        UIGraphicsBeginImageContextWithOptions(bounds.size,opaque,0)
        drawViewHierarchyInRect(bounds,afterScreenUpdates: true)
        let wholeImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

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

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

        // otherwise,grab specified `rect` of image

        let scale = image.scale
        let scaledRect = CGRect(x: rect.origin.x * scale,y: rect.origin.y * scale,width: rect.size.width * scale,height: rect.size.height * scale)
        guard let cgImage = CGImageCreateWithImageInRect(image.CGImage!,scaledRect) else { return nil }
        return UIImage(CGImage: cgImage,scale: scale,orientation: .Up)
    }

}

在Swift 3中:

extension UIView {

    /// Create snapshot
    ///
    /// - parameter rect: The `CGRect` of the portion of the view to return. If `nil` (or omitted),isOpaque,0)
        drawHierarchy(in: bounds,return image of whole view

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

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

}

要使用它,您可以:

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

以上是来客网为你收集整理的ios – 如何截取UIView的部分截图?全部内容,希望文章能够帮你解决ios – 如何截取UIView的部分截图?所遇到的程序开发问题。

如果觉得来客网网站内容还不错,欢迎将来客网网站推荐给程序员好友。