Capture UIView and Save as Image

前端 未结 7 544
孤城傲影
孤城傲影 2020-12-02 19:31

First of i Add the UILable on UIImageView and then after i screenshot the UIView, the image not proper capture the UIView

7条回答
  •  半阙折子戏
    2020-12-02 19:48

    In Swift 5 as extension:

    extension UIView {
    
        func takeSnapshot() -> UIImage? {
            UIGraphicsBeginImageContext(CGSize(width: self.frame.size.width, height: self.frame.size.height - 5))
            let rect = CGRect(x: 0.0, y: 0.0, width: self.frame.size.width, height: self.frame.size.height)
            drawHierarchy(in: rect, afterScreenUpdates: true)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image
        }
    }
    
    extension UIImage {
    
        func saveToPhotoLibrary(_ completionTarget: Any?, _ completionSelector: Selector?) {
            DispatchQueue.global(qos: .userInitiated).async {
                UIImageWriteToSavedPhotosAlbum(self, completionTarget, completionSelector, nil)
            }
        }
    }
    
    extension UIAlertController {
    
        func present() {
            guard let controller = UIApplication.shared.windows.filter({$0.isKeyWindow}).first?.rootViewController else {
                return
            }
            controller.present(self, animated: true)
        }
    }
    

    In your UIView sub class:

    func saveImage() {
        let selector = #selector(self.onImageSaved(_:error:contextInfo:))
        takeSnapshot()?.saveToPhotoLibrary(self, selector)
    }
    
    @objc private func onImageSaved(_ image: UIImage, error: Error?, contextInfo: UnsafeRawPointer) {
        if let error = error {
            let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "OK", style: .default))
            ac.present()
        } else {
            let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "OK", style: .default))
            ac.present()
        }
        onImageSaved?()
    }
    

提交回复
热议问题