我有一个从相机拍摄照片并将其放入 UIImageView 的应用程序。在您可以向其中添加小的“剪贴画”图片之后,这些图片将作为 subview 添加到 UIImageView(我的代码中为 tempImageView)。
但是当我尝试通过 tempImageView.image 将图像保存到相机时,图像变得更大,而且添加到它的 subview 也没有出现。知道如何将带有我的 subview 的 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)
}
感谢您的帮助。
最佳答案
您必须在图像上下文中绘制图像和 ImageView 的 subview ,并为该上下文“拍照”。我还没有测试过这段代码,但这会让你开始:
// 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)
关于ios - 如何将带有 subview 的 UIImageView 保存到相机胶卷?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38397199/