2017-02-19 74 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) 

} 
相关问题