请问我如何选择另一张透明图片并将其添加到另一张图片上?
透明图片如:小丑鼻子,帽子,帽子,耳环,小胡子,眼镜等.
它存在于几个应用程序但我无法找到任何关于此的Swift样本.
谢谢你的帮助.
我在UIImage扩展上有一个很好的功能:
extension UIImage {
static func imageByMergingImages(topImage: UIImage, bottomImage: UIImage, scaleForTop: CGFloat = 1.0) -> UIImage {
let size = bottomImage.size
let container = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 2.0)
UIGraphicsGetCurrentContext()!.interpolationQuality = .high
bottomImage.draw(in: container)
let topWidth = size.width / scaleForTop
let topHeight = size.height / scaleForTop
let topX = (size.width / 2.0) - (topWidth / 2.0)
let topY = (size.height / 2.0) - (topHeight / 2.0)
topImage.draw(in: CGRect(x: topX, y: topY, width: topWidth, height: topHeight), blendMode: .normal, alpha: 1.0)
return UIGraphicsGetImageFromCurrentImageContext()!
}
}
Run Code Online (Sandbox Code Playgroud)
所以你可以这样打电话:
let image = UIImage.imageByMergingImages(topImage: top, bottomImage: bottom)
Run Code Online (Sandbox Code Playgroud)
对于您的特定情况,考虑到要在图像上添加许多叠加层,您应该具有如下函数:
extension UIImage {
func imageOverlayingImages(_ images: [UIImage], scalingBy factors: [CGFloat]? = nil) -> UIImage {
let size = self.size
let container = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 2.0)
UIGraphicsGetCurrentContext()!.interpolationQuality = .high
self.draw(in: container)
let scaleFactors = factors ?? [CGFloat](repeating: 1.0, count: images.count)
for (image, scaleFactor) in zip(images, scaleFactors) {
let topWidth = size.width / scaleFactor
let topHeight = size.height / scaleFactor
let topX = (size.width / 2.0) - (topWidth / 2.0)
let topY = (size.height / 2.0) - (topHeight / 2.0)
image.draw(in: CGRect(x: topX, y: topY, width: topWidth, height: topHeight), blendMode: .normal, alpha: 1.0)
}
return UIGraphicsGetImageFromCurrentImageContext()!
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以用这种方式组合你的最终图像:
var imageClownFace = UIImage(named: "clown_face")!
imageClownFace = imageClownFace.imageOverlayingImages([imageNose, imageHat, imageCap])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2284 次 |
| 最近记录: |