簡體   English   中英

將UIView轉換為UIImage Swift 3

[英]Convert UIView to UIImage Swift 3

我正在開發將UIView轉換為UIImage的擴展程序,但是遇到一個奇怪的問題,我可以在iOS Simulator中獲取正確的圖像,但在真實設備中卻得到黑色圖像。 下面是我的代碼

extension UIView {
func screenshotImage() -> UIImage {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0.0);
    self.drawHierarchy(in: self.bounds, afterScreenUpdates: true)
    let screenShot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return screenShot!
}
}

誰能解釋我在真實設備中無法獲得正確圖像的錯誤做法?

編輯

觀察結果:

每當我將UIView傳遞給模擬器中的此擴展程序時,我都會獲得該視圖的完美圖像

每當我在真實設備中將UIView傳遞給此擴展時,我都會得到一張全黑的圖像,而不是該UIView中的元素(與模擬器結果不同)。

extension UIImage {
    class func imageWithView(view: UIView) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0)
        view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }
}

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM