因此,在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的部分截图?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)