ios - 如何将带有 subview 的 UIImageView 保存到相机胶卷?

标签 ios swift uiimageview

我有一个从相机拍摄照片并将其放入 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/

相关文章:

ios - UIImageView:获取转换后的 UIImage

ios - swift 真实图像高度

ios - 数据库观察者函数在viewDidLoad中不充当观察者,仅充当viewDidAppear

ios - 在 iOS 6 上开始播放视频时 MPMoviePlayerController 崩溃

ios - OpenEars 语音识别将其他单词检测为正确单词

ios - 如何显示导航左栏按钮?

iphone - 如何在 iOS 中为图像添加三边边框

ios - iOS7 中的奇怪空间

ios - UIImage 不会显示带有白色前景图案的 PNG

ios - 首次加载时 UICollectionViewCell 内容大小错误