Swift UIView具有乘法效果

时间:2015-12-27 18:12:59

标签: ios xcode swift uiimageview swift2

我几个小时试图达到的目标如下: enter image description here

我希望在背景中有UIImage,然后最好是UIView,背景颜色为红色,带有某种倍增效果(红色区域)。这可能吗?我已经看到UIImage的一些扩展为它们着色,但只有当我希望我的整个图像具有红色的多色效果时才会起作用。

谢谢

3 个答案:

答案 0 :(得分:9)

您只需在convolver.connect(context.destination)的顶部添加红色UIView即可。调整alpha以使其透明:

UIImageView

使用乘法代替:

let someView = UIView(frame: someImageView.frame)
someView.backgroundColor = UIColor(colorLiteralRed: 255.0/255.0, green: 0, blue: 0, alpha: 0.5)
someImageView.addSubview(someView)

答案 1 :(得分:4)

Swift 3 扩展(thx到@Kex):

extension UIImage{
    class func multiply(image:UIImage, color:UIColor) -> UIImage? {
        let rect = CGRect(origin: .zero, size: image.size)

        //image colored
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
        color.setFill()
        UIRectFill(rect)
        let coloredImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        //image multiply
        UIGraphicsBeginImageContextWithOptions(image.size, true, 0)
        let context = UIGraphicsGetCurrentContext()

        // fill the background with white so that translucent colors get lighter
        context!.setFillColor(UIColor.white.cgColor)
        context!.fill(rect)

        image.draw(in: rect, blendMode: .normal, alpha: 1)
        coloredImage?.draw(in: rect, blendMode: .multiply, alpha: 1)

        let result = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return result
    }
}

示例:

let image = UIImage.multiply(image: sourceImage, color: UIColor.red)

答案 2 :(得分:4)

使用 iOS10 ,您现在可以使用UIGraphicsImageRenderer添加部分乘法效果,就像这样简单:

extension UIImage {
    func tinted(_ color: UIColor, percentageFromBottom: CGFloat) -> UIImage? {
        let imageRect = CGRect(origin: .zero, size: size)
        let colorRect = CGRect(x: 0, y: (1.0 - percentageFromBottom) * size.height, width: size.width, height: percentageFromBottom * size.height)
        let renderer = UIGraphicsImageRenderer(size: size)

        let tintedImage = renderer.image { context in
            color.set()
            context.fill(colorRect)
            draw(in: imageRect, blendMode: .multiply, alpha: 1)
        }

        return tintedImage
    }
}

然后您可以像这样使用它来将原稿的下三分之一乘以红色乘法:

UIImage(named: "trees")?.tinted(.red, percentageFromBottom: 0.33)

结果如下:

enter image description here