min*_*eek 10 iphone image swift
我正在学习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)
}
Run Code Online (Sandbox Code Playgroud)
但是,这是有效的,现在已经不复存在了.但是,这也不是最好的解决方案.
所以,伙计们,如何将图像从个人图像保存到相机胶卷,图像为叠加?
非常感谢帮助!! 谢谢!
cno*_*oon 26
我建议通过这个帖子阅读.你的所有答案都在那里.阅读完该文章后,以下代码示例可帮助您将两个图像正确合成.
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()
}
Run Code Online (Sandbox Code Playgroud)
希望这能让你朝着正确的方向前进.
Adr*_*ian 11
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))
}
}
Run Code Online (Sandbox Code Playgroud)
除了性能提升之外,您还可以获得完整的 P3 范围。
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()
}
Run Code Online (Sandbox Code Playgroud)
要使用图像只需参考 newImage
如何使用图像的示例:
@IBOutlet weak var imageButton: UIButton!
imageButton.setBackgroundImage(newImage), for: .normal)
Run Code Online (Sandbox Code Playgroud)
这是对cnoon 答案的编辑,但针对 Swift 4 进行了优化。