Ubah UIView Anda menjadi gambar dengan drawViewHierarchyInRect: afterScreenUpdates: yang jauh lebih cepat daripada renderInContext
Catatan penting: jangan panggil fungsi ini dari viewDidLoad atau viewWillAppear , pastikan Anda menangkap tampilan setelah itu ditampilkan / dimuat sepenuhnya
Obj C
UIGraphicsBeginImageContextWithOptions(myView.bounds.size, myView.opaque, 0.0f);
[myView drawViewHierarchyInRect:myView.bounds afterScreenUpdates:NO];
UIImage *snapshotImageFromMyView = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
myImageView.image = snapshotImageFromMyView;
Simpan album foto gambar yang diedit
UIImageWriteToSavedPhotosAlbum(snapshotImageFromMyView, nil,nil, nil);
Cepat 3/4
UIGraphicsBeginImageContextWithOptions(myView.bounds.size, myView.isOpaque, 0.0)
myView.drawHierarchy(in: myView.bounds, afterScreenUpdates: false)
let snapshotImageFromMyView = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
print(snapshotImageFromMyView)
myImageView.image = snapshotImageFromMyView
Generalisasi super mudah dengan ekstensi, iOS11, swift3 / 4
extension UIImage{
convenience init(view: UIView) {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0)
view.drawHierarchy(in: view.bounds, afterScreenUpdates: false)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.init(cgImage: (image?.cgImage)!)
}
}
Use :
imgVV.image = UIImage.init(view: myView)
let img = UIImage.init(view: myView)