2017-02-19 20 views
0

我在Stackoverflow上看到了幾十個類似的問題。合併縮減視圖的圖像與子視圖的圖像保留原始大小

儘管他們都沒有幫助。我有一個應用程序,在其中製作照片,然後在照片上添加一些圖像。然後,我需要將拍攝的照片與我放在其上的圖像一起保存。這裏是我的結構看起來像:

enter image description here

正如你可以看到我有Photo ViewPhoto Scroll View。作爲子視圖,每個添加的貼紙進入Photo Scroll View

現在,我該如何合併來自Photo Scroll View的所有圖像到一個圖像中。到目前爲止,我已經設法將它保存爲一個絕對太小的屏幕大小。

func saveImage(_ sender: Any) { 

    //Create the UIImage 
    UIGraphicsBeginImageContext(photoScrollView.frame.size) 
    photoScrollView.layer.render(in: UIGraphicsGetCurrentContext()!) 
    let image = UIGraphicsGetImageFromCurrentImageContext()! 
    UIGraphicsEndImageContext() 

    //Save it to the camera roll 
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) 

} 

此外,我試圖通過創建快照。在這種情況下,圖像只包含白色屏幕,沒有其他東西(並且它不是任何視圖的背景顏色)。

func saveImage(_ sender: Any) { 

    let snapShot:UIView = self.photoScrollView.snapshotView(afterScreenUpdates: true)! 
    UIGraphicsBeginImageContext(self.photoScrollView.bounds.size) 
    snapShot.drawHierarchy(in: self.photoScrollView.bounds, afterScreenUpdates: true) 

    let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()! 
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) 

} 

任何人都可以幫助我嗎?

+0

使用的第一次嘗試,調用'photoScrollView.draw(RECT:photoScrollView.frame)' –

+0

@gkchristopher我換成'photoScrollView.layer.render(在:UIGraphicsGetCurrentContext ()!)'帶'photoScrollView.draw(rect:photoScrollView.frame)''。沒有幫助。結果只是一張白色圖片,而'photoScrollView'背景爲綠色。 –

回答

0

在嘗試了各種方法後,我找到了一個解決方案,將Photo View包裝在一個簡單的UIView(我稱之爲placeholderView)中。所有添加的圖像作爲子視圖放入placeholderView,因此它們與photoView處於同一級別。

因此我有結構:Photo Scroll View -> placeholderView-> ALL_OTHER_SUBVIEWS。 由背景照片和在其上面添加的圖像組成。

,代碼如下:

@IBAction func saveImage(_ sender: Any) { 

    //Create the UIImage 
    let zoomVal = photoScrollView.zoomScale 
    photoScrollView.zoomScale = 1.0 

    UIGraphicsBeginImageContext(placeholderView.frame.size) 
    placeholderView.layer.render(in: UIGraphicsGetCurrentContext()!) 
    let image = UIGraphicsGetImageFromCurrentImageContext()! 
    UIGraphicsEndImageContext() 
    photoScrollView.zoomScale = zoomVal 
    //Save it to the camera roll 
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) 

} 
相關問題