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

ios – 如何截取UIView的部分截图?,第1张

概述我希望用户在我的应用程序中使用 Swift中的编程按钮按下应用程序的屏幕截图.我知道UIGraphicsGetImageFromCurrentImageContext()需要截图,但我不想要整个屏幕的图片.我希望d出一个矩形(有点像裁剪工具),用户可以拖动矩形并调整其大小,只截取屏幕的某个部分.我希望矩形遍历WKWebView并裁剪网页视图的图片. 标准快照技术是drawViewHierarchy 我希望用户在我的应用程序中使用 Swift中的编程按钮按下应用程序的屏幕截图.我知道UIGraphicsGetimageFromCurrentimageContext()需要截图,但我不想要整个屏幕的图片.我希望d出一个矩形(有点像裁剪工具),用户可以拖动矩形并调整其大小,只截取屏幕的某个部分.我希望矩形遍历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的部分截图?所遇到的程序开发问题。

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1109186.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)

保存