问题描述
我一直在尝试合并两张图片,一张在顶部,另一张在底部。下面的这段代码似乎不起作用。 x 协调器是正确的,但 y 似乎不对,当我改变它时它会裁剪顶部图像。我做错了什么?
func combine(bottomImage: Data,topImage: Data) -> UIImage {
let bottomImage = UIImage(data: topImage)
let topImage = UIImage(data: bottomImage)
let size = CGSize(width: bottomImage!.size.width,height: bottomImage!.size.height + topImage!.size.height)
UIGraphicsBeginImageContext(size)
let areaSizeb = CGRect(x: 0,y: 0,width: bottomImage!.size.width,height: bottomImage!.size.height)
let areaSize = CGRect(x: 0,width: topImage!.size.width,height: topImage!.size.height)
bottomImage!.draw(in: areaSizeb)
topImage!.draw(in: areaSize)
let newImage = UIGraphicsGetimageFromCurrentimageContext()!
UIGraphicsEndImageContext()
return newImage
}
解决方法
您正在将两个图像绘制到同一个矩形中。您也不应该使用强制展开。如果出现任何问题,这会导致您的应用崩溃。
还有其他各种小错误。
像这样改变你的函数:
// Return an Optional so we can return nil if something goes wrong
func combine(bottomImage: Data,topImage: Data) -> UIImage? {
// Use a guard statement to make sure
// the data can be converted to images
guard
let bottomImage = UIImage(data: bottomImage),let topImage = UIImage(data: topImage) else {
return nil
}
// Use a width wide enough for the widest image
let width = max(bottomImage.size.width,topImage.size.width)
// Make the height tall enough to stack the images on top of each other.
let size = CGSize(width: width,height: bottomImage.size.height + topImage.size.height)
UIGraphicsBeginImageContext(size)
let bottomRect = CGRect(
x: 0,y: 0,width: bottomImage.size.width,height: bottomImage.size.height)
// Position the bottom image under the top image.
let topRect = CGRect(
x: 0,y: bottomImage.size.height,width: topImage.size.width,height: topImage.size.height)
bottomImage.draw(in: bottomRect)
topImage!.draw(in: topRect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
(你真的应该使用 UIGraphicsImageRenderer 而不是调用 UIGraphicsBeginImageContext()
/ UIGraphicsEndImageContext()
。)
编辑:
请注意,如果 2 张图片的宽度不同,上面的代码会在较窄的图片右侧留下一个“死角”。您还可以使代码中心的图像较窄,或将其放大到相同的宽度。 (如果你确实放大了,我建议在两个维度上都放大以保持原始纵横比。否则它看起来会被拉伸和不自然。)