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

前端之家收集整理的这篇文章主要介绍了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
}
原文链接:https://www.f2er.com/iOS/335403.html

猜你在找的iOS相关文章