对于一个视图的绘制,只需使用以下命令:
// Begin context
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.mainScreen().scale)
// Draw view in that context
drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
// And finally, get image
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
如果您想多次使用它,扩展可能会完成以下任务:
//迅捷4
extension UIView {
func takeScreenshot() -> UIImage {
// Begin context
UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.main.scale)
// Draw view in that context
drawHierarchy(in: self.bounds, afterScreenUpdates: true)
// And finally, get image
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if (image != nil)
{
return image!
}
return UIImage()
}
}
//老Swift
extension UIView {
func takeScreenshot() -> UIImage {
// Begin context
UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.mainScreen().scale)
// Draw view in that context
drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)
// And finally, get image
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
要解释这些参数的作用:
UIGraphicsBeginImageContextWithOptions()创建临时呈现
更多信息请点击这里
至于抽签,Apple Docs将其解释为细节here和here