Swift:在没有TabBar和NavigationBar的情况下裁剪屏幕截图

Ran*_*oms 6 screenshot cgimage ios uigraphicscontext swift

我有整个屏幕的截图screenshot,使用以下内容生成:

let layer = UIApplication.sharedApplication().keyWindow!.layer
let scale = UIScreen.mainScreen().scale
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);

layer.renderInContext(UIGraphicsGetCurrentContext())
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
Run Code Online (Sandbox Code Playgroud)

我想裁剪它,以便不包括标签栏,我尝试使用以下代码:

let crop = CGRectMake(0, 0, //"start" at the upper-left corner
self.view.bounds.width, //include half the width of the whole screen
self.view.bounds.height + self.navigationController!.navigationBar.frame.height) //include the height of the navigationBar and the height of view

let cgImage = CGImageCreateWithImageInRect(screenshot.CGImage, crop)
let image: UIImage = UIImage(CGImage: cgImage)!
Run Code Online (Sandbox Code Playgroud)

此代码image仅显示屏幕的一小部分,从屏幕左上角开始的矩形(0,0),向右延伸不到屏幕宽度的一半,然后向下不到一半屏幕的高度.不过,我想要包括整个屏幕,除了标签栏占用的区域.有没有这种方法来裁剪它?

sah*_*108 8

根据这个

新图像是通过
1)rect通过调用调整到整数边界来创建的CGRectIntegral;
2)将结果与原点(0,0)和大小等于大小的矩形相交image;
3)参考所得矩形内的像素,将图像数据的第一像素视为图像的原点.
如果生成的矩形是空矩形,则此函数返回NULL.

如果W和H分别是图像的宽度和高度,则点(0,0)对应于图像数据的第一像素; 点(W-1,0)是图像数据的第一行的最后一个像素; (0,H-1)是图像数据的最后一行的第一个像素; (W-1,H-1)是图像数据最后一行的最后一个像素.

你需要有这样的裁剪功能.您可能需要调整计算bottomBarHeight

func takeScreenshot(sender: AnyObject) {
    let layer = UIApplication.sharedApplication().keyWindow!.layer
    let scale = UIScreen.mainScreen().scale
    UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);

    layer.renderInContext(UIGraphicsGetCurrentContext())
    let screenshot = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    let croppedImage = self.cropImage(screenshot)
}

func cropImage(screenshot: UIImage) -> UIImage {
    let scale = screenshot.scale
    let imgSize = screenshot.size
    let screenHeight = UIScreen.mainScreen().applicationFrame.height
    let bound = self.view.bounds.height
    let navHeight = self.navigationController!.navigationBar.frame.height
    let bottomBarHeight = screenHeight - navHeight - bound
    let crop = CGRectMake(0, 0, //"start" at the upper-left corner
        (imgSize.width - 1) * scale, //include half the width of the whole screen
        (imgSize.height - bottomBarHeight - 1) * scale) //include the height of the navigationBar and the height of view

    let cgImage = CGImageCreateWithImageInRect(screenshot.CGImage, crop)
    let image: UIImage = UIImage(CGImage: cgImage)!
    return image
}
Run Code Online (Sandbox Code Playgroud)