An empty snapshotView on iPhone 7/7plus

前端 未结 2 1100
小鲜肉
小鲜肉 2021-02-19 19:30

My first question here:) Recently I update my Xcode to 8, and the resizableSnapshotView method doesn\'t work properly on some simulators. The snapshotView works we

相关标签:
2条回答
  • 2021-02-19 20:12

    Works in:

    • Version 8.1 (8B62)
    • Simulator Version 10.0 (SimulatorApp-700.14

    Swift 3

    import Foundation
    import UIKit
    
    extension UIView {
        func snapshotView() -> UIView? {
            guard let image = snapshotImage() else { return nil }
            return UIImageView(image: image)
        }
    
        func snapshotImage() -> UIImage? {
            UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, contentScaleFactor)
            defer { UIGraphicsEndImageContext() }
    
            drawHierarchy(in: bounds, afterScreenUpdates: false)
    
            return UIGraphicsGetImageFromCurrentImageContext()
        }
    }
    
    0 讨论(0)
  • 2021-02-19 20:18

    Use the following UIView extension to create a snapshot using CoreGraphics.

    I can confirm this works on iPhone 7 simulator.

    public extension UIView {
    
        public func snapshotImage() -> UIImage? {
            UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
            drawHierarchy(in: bounds, afterScreenUpdates: false)
            let snapshotImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return snapshotImage
        }
    
        public func snapshotView() -> UIView? {
            if let snapshotImage = snapshotImage() {
                return UIImageView(image: snapshotImage)
            } else {
                return nil
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题