2016-07-15 69 views
0

我有一个应用程序,从相机拍摄图片并将其放入UIImageView中。之后,你可以添加小的“剪贴画”图片,它被添加为UIImageView(我的代码中的tempImageView)的子视图。如何将UIImageView与子视图保存到相机胶卷?

但是,当我尝试通过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

您必须在图像上下文中绘制图像和图像视图的子视图,并在该上下文中“拍摄图片”。我没有测试此代码,但是这将让你开始:

// 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) 
+0

非常感谢!这样做的伎俩,如果有人想知道我也不需要重复我的tempImageViews子视图。 – nullforlife

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是您应该存储的最终图像。

+0

谢谢,这可能与我所看到的一样好,但我使用了keithbhunter的解决方案,这些解决方案有点更具说明性。 – nullforlife

+0

不客气.... :) – Lion

相关问题