我有一个名为overView的UIView:
overView.frame = CGRectMake(self.view.frame.width/25, self.view.frame.height/25, self.view.frame.width/1.3, self.view.frame.height/1.2)
我只想截取此视图的屏幕截图,而不是整个屏幕。并制作尺寸截图:
(CGSizeMake(2480,3508 )
这是我的代码:
UIGraphicsBeginImageContextWithOptions(CGSizeMake(2480,3508 ), false, 0); self.view.drawViewHierarchyInRect(CGRectMake(-self.view.frame.width/25, -self.view.frame.height/25,2480,3508), afterScreenUpdates: true) var image:UIImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext()
屏幕截图具有所需的大小,但是它需要整个视图的屏幕截图,而不仅仅是“ overView”。
要绘制一个视图,只需使用以下命令:
// 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()
如果您想多次使用它,可能扩展可以完成这项工作:
// Swift4
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()创建一个临时渲染上下文,在其中绘制原始文档。第一个参数size是缩放图像的目标大小。第二个参数isOpaque用于确定是否渲染Alpha通道。对于不透明的图像(即Alpha通道),将其设置为false可能导致图像具有粉红色的色调。第三个参数比例是显示比例因子。设置为0.0时,将使用主屏幕的比例因子,对于Retina显示屏,该比例因子为2.0或更高(iPhone 6 Plus为3.0)。
有关此的更多信息,请参见http://nshipster.com/image-resizing/
至于抽奖电话,Apple Docs 在此处和此处详细解释