2017-08-31 110 views
1

我有以下代碼:的iOS - 滾動型屏幕截圖示出灰色部分

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 
} 

層次結構是這樣的:查看 - >滾動型 - >查看 - >剩餘的視圖

滾動視圖的屏幕截圖,問題是爲什麼底部沒有着色。

enter image description here

截圖內視圖。

enter image description here

應該如何看起來像

enter image description here

+0

是你所有的觀點是滾動型的子視圖,或者你有持有所有看法容器看法? –

+0

是這樣的:查看 - > ScrollView - >查看 - >其餘視圖 – Ricardo

+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 
} 
+0

刪除'scrollview.layer.render'後只有'drawHierarchy(in:self.bounds,afterScreenUpdates:true)'Working? –

+1

我不得不添加它。 – Ricardo