我正在学习Swift,我正在创建一个使用个人照片并将另一个放在其上的应用程序。我现在有一个hacky解决方案,创建该区域的屏幕截图并保存。我需要在Swift中执行此操作
@IBAction func saveImage(sender: AnyObject) {
//Create the UIImage
UIGraphicsBeginImageContext(imageView.frame.size)
view.layer.renderInContext(UIGraphicsGetCurrentContext())
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
//Save it to the camera roll
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
但是,这是有效的,现在已经不复存在了。但是,这也不是最好的解决方案。
那么伙计们,如何将图像从个人图像保存到相机胶卷,图像为叠加?
帮助将不胜感激!!谢谢!
答案 0 :(得分:25)
我建议通过this线程阅读。你的所有答案都在那里。阅读完本文后,以下代码示例应该可以帮助您将两个图像合理地合成在一起。
func saveImage() {
let bottomImage = UIImage(named: "bottom")!
let topImage = UIImage(named: "top")!
let newSize = CGSizeMake(100, 100) // set this to what you need
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
bottomImage.drawInRect(CGRect(origin: CGPointZero, size: newSize))
topImage.drawInRect(CGRect(origin: CGPointZero, size: newSize))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
希望这能让你朝着正确的方向前进。
答案 1 :(得分:4)
SWIFT 4更新
func saveImage() {
let bottomImage = UIImage(named: "your bottom image name")!
let topImage = UIImage(named: "your top image name")!
let newSize = CGSize(width: 100, height: 100) // set this to what you need
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
bottomImage.draw(in: CGRect(origin: CGPoint.zero, size: newSize))
topImage.draw(in: CGRect(origin: CGPoint.zero, size: newSize))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
要使用图片,请参阅newImage
示例如何使用图像:
@IBOutlet weak var imageButton: UIButton!
imageButton.setBackgroundImage(newImage), for: .normal)
这是cnoon's answer的编辑,但针对Swift 4进行了优化。
答案 2 :(得分:3)
更新到Swift 3.0:
func saveImage() {
let bottomImage = UIImage(named: "bottom")!
let topImage = UIImage(named: "top")!
let newSize = CGSizeMake(100, 100) // set this to what you need
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
bottomImage.draw(in: CGRect(origin: CGPointZero, size: newSize))//As drawInRect is deprecated
topImage.draw(at: CGRect(origin: CGPointZero, size: newSize))//As drawInRect is deprecated
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
答案 3 :(得分:0)
Apple建议不要使用UIGraphicsBeginImageContext,因此,只要您的应用支持iOS 10之前的设备,就可以使用以下命令:
private func drawLogoIn(_ image: UIImage, _ logo: UIImage, position: CGPoint) -> UIImage {
let renderer = UIGraphicsImageRenderer(size: image.size)
return renderer.image { context in
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
logo.draw(in: CGRect(origin: position, size: logo.size))
}
}
除了性能提升之外,您还可以获得完整的P3范围。