Swift:如何将图像添加到另一个图像?

时间:2017-11-16 07:14:24

标签: ios swift uiimage

请您指导我如何选择另一张透明图片并将其添加到另一张图片的正确路径? 透明图片如:小丑鼻子,帽子,帽子,耳环,小胡子,眼镜等 它存在于几个应用程序中,但我无法找到任何关于此的Swift示例。

感谢您的帮助。

1 个答案:

答案 0 :(得分:5)

我在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()!
    }

}

所以你可以这样打电话:

let image = UIImage.imageByMergingImages(topImage: top, bottomImage: bottom)

对于您的具体情况,考虑到您想在图像上添加许多叠加层,您应该有这样的功能:

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()!
    }

}

然后你可以用这种方式谱写你的最终图像:

var imageClownFace = UIImage(named: "clown_face")!
imageClownFace = imageClownFace.imageOverlayingImages([imageNose, imageHat, imageCap])