Swift 没有空格的截屏?

Swift 没有空格的截屏?,swift,Swift,我在一个视图上有一些png,我在其中捕获了一幅图像: let rect: CGRect = self.frame UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0); let context: CGContext = UIGraphicsGetCurrentContext()! self.layer.render(in: context) let img: UI

我在一个视图上有一些png,我在其中捕获了一幅图像:

let rect: CGRect = self.frame
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0);
        let context: CGContext = UIGraphicsGetCurrentContext()!
        self.layer.render(in: context)
        let img: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
问题是,我想要得到一个最终的png大小作为视图上内容的大小,而不是一个恒定的矩形大小


因此,如果较低的内容以50px开始,最大内容以200px结束,我的新png的高度将为150。

您应该在视图中迭代以检测内容的边界

您可以手动计算帧:

var minX = view.frame.origin.x + view.frame.size.width
var minY = view.frame.origin.y + view.frame.size.height
var maxX = 0
var maxY = 0

for subview in self.subviews {
    minX = min(minX, subview.frame.origin.x)
    minY = min(minY, subview.frame.origin.y)
    maxX = max(maxX, subview.frame.origin.x + subview.frame.size.width)
    maxY = max(maxY, subview.frame.origin.y + subview.frame.size.height)
}

var newPngRect = CGRect(x: minX, y: minY, width: maxX-minX, height: maxY-minY)

UIGraphicsBeginImageContextWithOptions(newPngRect!, false, 0.0)
var newPngRect = CGRect.zero
for subview in subviews {
    baseRect = baseRect.union(subview.frame)
}

UIGraphicsBeginImageContextWithOptions(newPngRect, false, 0.0)
确定子视图的位置

var minX = view.frame.origin.x + view.frame.size.width
var minY = view.frame.origin.y + view.frame.size.height
var maxX = 0
var maxY = 0

for subview in self.subviews {
    minX = min(minX, subview.frame.origin.x)
    minY = min(minY, subview.frame.origin.y)
    maxX = max(maxX, subview.frame.origin.x + subview.frame.size.width)
    maxY = max(maxY, subview.frame.origin.y + subview.frame.size.height)
}

var newPngRect = CGRect(x: minX, y: minY, width: maxX-minX, height: maxY-minY)

UIGraphicsBeginImageContextWithOptions(newPngRect!, false, 0.0)
var newPngRect = CGRect.zero
for subview in subviews {
    baseRect = baseRect.union(subview.frame)
}

UIGraphicsBeginImageContextWithOptions(newPngRect, false, 0.0)

如果需要,可以将
yourContentView.subview
替换为
yourContentView.subview

创建一个视图,其中包含要截屏的所有子视图(a
containerView

使用“自动布局”可以根据需要布局其所有子视图

准备截图视图时,请使用:

UIGraphicsBeginImageContextWithOptions(containerView.frame.size, false, 0.0);
let context: CGContext = UIGraphicsGetCurrentContext()!
containerView.layer.render(in: context)
let img: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()

我认为这在某些情况下是错误的。假设有1个子视图,位于(1,1),宽度为1,高度为1。这将使最小值为0,最小值为0,宽度/高度为1。更安全的/不太手动的解决方案是将你关心的所有视图都放在1视图中,并在其ReCt上调用<代码> UpStudioSeCimeEngEngType选项>代码>康纳。如果在(2,2)处添加另一个子视图,则会发生相同的错误。
minX
minY
的逻辑错误。Ofc,因为初始值应大于屏幕原点。现在应该可以了谢谢,但这是什么?你复制我的密码?这就是我所做的,它将创建空间。它与您的代码不同。我解释了怎么做,你解决了吗?