如何截取屏幕的一部分

How to screenshot just part of a screen

我需要将图像裁剪为高度为 25、宽度为屏幕长度的矩形。

我已准备好图像并将其放置在屏幕中央。我只想截取矩形。

我关注了 ,但由于某些原因它似乎对我不起作用。

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.view.frame.width,25), false, 0)

    self.view.drawViewHierarchyInRect(CGRectMake(self.view.frame.width,25,view.bounds.size.width,view.bounds.size.height), afterScreenUpdates: true)

    let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    statusImage = image

您使用的坐标有误。使用您的代码,绘图从视图的右上角开始,并在其右侧绘制 void space 。您应该使用 0 作为 X 值和负 Y 值。例如,如果你想截图一个从 Y=50 开始的柱,你应该使用:

self.view.drawViewHierarchyInRect(CGRectMake(0, -50, view.bounds.size.width, view.bounds.size.height), afterScreenUpdates: true)

如果要从视图的顶部绘制,只需将 0 作为 Y 值即可。