如何将带有子视图的UIImageView保存到相机胶卷?

时间:2016-07-15 13:19:44

标签: ios swift uiimageview

我有一个应用程序从相机拍摄照片并将其放入UIImageView。之后你可以添加小"剪贴画"它的图片,作为子视图添加到UIImageView(我的代码中的tempImageView)。

但是当我尝试通过tempImageView.image将图像保存到相机时,图像变得更大,并且添加到其中的子视图也没有出现。知道如何用我的子视图将UIImageView保存到相机胶卷吗?

以下是我保存图片的方式:

@IBAction func saveImageButtonPressed(sender: UIButton) {

    UIImageWriteToSavedPhotosAlbum(tempImageView.image!, self, "image:didFinishSavingWithError:contextInfo:", nil)
}

func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) {
    if error == nil {
        let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .Alert)
        ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
        presentViewController(ac, animated: true, completion: nil)
    } else {
        let ac = UIAlertController(title: "Save error", message: error?.localizedDescription, preferredStyle: .Alert)
        ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
        presentViewController(ac, animated: true, completion: nil)
    }
}

以下是我如何将图片添加到我的tempImageView:

@IBAction func berlockButtonPressed(sender: UIButton) {
    let imageName = "berlock.png"
    let image = UIImage(named: imageName)
    let imageView = UIImageView(image: image!)
    imageView.frame = CGRect(x: 200, y: 200, width: 60, height: 100)

    tempImageView.addSubview(imageView)
}

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

您必须在图像上下文中绘制图像和图像视图的子视图,并对该上下文进行“拍照”。我没有测试过这段代码,但这会让你开始:

// Create the image context to draw in
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, UIScreen.mainScreen().scale)

// Get that context
let context = UIGraphicsGetCurrentContext()

// Draw the image view in the context
imageView.layer.renderInContext(context!)

// You may or may not need to repeat the above with the imageView's subviews  
// Then you grab the "screenshot" of the context
let image = UIGraphicsGetImageFromCurrentImageContext()

// Be sure to end the context
UIGraphicsEndImageContext()

// Finally, save the image
UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)

答案 1 :(得分:0)

你应该渲染类似的图像,

   UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, imageView.opaque, 0.0)

    imageView.layer.renderInContext(UIGraphicsGetCurrentContext()!)

     let resultImageToStore = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

您可以提供所需的尺寸,而不是imageView.bounds.sizeimageView.bounds.size保持您的imageview的大小。

imageView视为具有其他子视图的imageView。

resultImageToStore是您应存储的最终图片。