iOS - Scrollview截图显示灰色部分

时间:2017-08-31 11:32:30

标签: ios swift

我有以下代码:

func takeScrollScreenshot() -> UIImage? {

    let scrollview: UIScrollView = self as! UIScrollView
    UIGraphicsBeginImageContext(scrollview.contentSize)
    let savedContentOffset = scrollview.contentOffset
    let savedFrame = scrollview.frame
    scrollview.contentOffset = CGPoint.zero;
    scrollview.frame = CGRect(x: CGFloat(0),
                              y: CGFloat(0),
                              width: scrollview.contentSize.width,
                              height: scrollview.contentSize.height);
    scrollview.layer.render(in: UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext();
    scrollview.contentOffset = savedContentOffset
    scrollview.frame = savedFrame
    UIGraphicsEndImageContext()

    return image
}

层次结构如下:查看 - > ScrollView - >查看 - >其余的观点

scrollview截图,问题是为什么底部没有着色。

enter image description here

内部视图的屏幕截图。

enter image description here

应该怎么样?

enter image description here

1 个答案:

答案 0 :(得分:1)

我找到了解决方案。 我只需添加第drawHierarchy(in: self.bounds, afterScreenUpdates: true)

func takeScrollScreenshot() -> UIImage? {

    let scrollview: UIScrollView = self as! UIScrollView
    UIGraphicsBeginImageContext(scrollview.contentSize)
    let savedContentOffset = scrollview.contentOffset
    let savedFrame = scrollview.frame
    scrollview.contentOffset = CGPoint.zero;
    scrollview.frame = CGRect(x: CGFloat(0),
                              y: CGFloat(0),
                              width: scrollview.contentSize.width,
                              height: scrollview.contentSize.height);
    scrollview.layer.render(in: UIGraphicsGetCurrentContext()!)

    //I forget add this line.
    drawHierarchy(in: self.bounds, afterScreenUpdates: true)

    let image = UIGraphicsGetImageFromCurrentImageContext();
    scrollview.contentOffset = savedContentOffset
    scrollview.frame = savedFrame
    UIGraphicsEndImageContext()

    return image
}