2016-07-15 114 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

相關問題