本文介绍了在Swift中混合UIColors的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个SKSpriteNode,它们的颜色定义如下:

I have two SKSpriteNode and their colors are defined like this:

colorNode[0].color = UIColor(red: 255, green: 0, blue: 0, alpha: 1)
colorNode[1].color = UIColor(red: 0, green: 255, blue: 0, alpha: 1)

我想让第三个SKSpriteNode带有两个前两个的混合色,结果应该是这样的:

and I want to have a third SKSpriteNode colorized with a blend of the two first ones, the result should be like this :

colorNode[2].color = UIColor(red: 255, green: 255, blue: 0, alpha: 1)

但是有没有办法添加两个UIColors?像这样:

but is there a way to addition two UIColors ? Like this :

colorNode[2].color = colorNode[0].color + colorNode[1].color

推荐答案

这样的事情如何?

func addColor(_ color1: UIColor, with color2: UIColor) -> UIColor {
    var (r1, g1, b1, a1) = (CGFloat(0), CGFloat(0), CGFloat(0), CGFloat(0))
    var (r2, g2, b2, a2) = (CGFloat(0), CGFloat(0), CGFloat(0), CGFloat(0))

    color1.getRed(&r1, green: &g1, blue: &b1, alpha: &a1)
    color2.getRed(&r2, green: &g2, blue: &b2, alpha: &a2)

    // add the components, but don't let them go above 1.0
    return UIColor(red: min(r1 + r2, 1), green: min(g1 + g2, 1), blue: min(b1 + b2, 1), alpha: (a1 + a2) / 2)
}

func multiplyColor(_ color: UIColor, by multiplier: CGFloat) -> UIColor {
    var (r, g, b, a) = (CGFloat(0), CGFloat(0), CGFloat(0), CGFloat(0))
    color.getRed(&r, green: &g, blue: &b, alpha: &a)
    return UIColor(red: r * multiplier, green: g * multiplier, blue: b * multiplier, alpha: a)
}

定义运算符以添加颜色并将颜色乘以Double:

Define operators to add colors and multiply a color by a Double:

func +(color1: UIColor, color2: UIColor) -> UIColor {
    return addColor(color1, with: color2)
}

func *(color: UIColor, multiplier: Double) -> UIColor {
    return multiplyColor(color, by: CGFloat(multiplier))
}

然后,您可以像这样混合颜色:

Then you can blend colors like this:

// Make orange with 50% red and 50% yellow
let orange = .red * 0.5 + .yellow * 0.5

// Make light gray with 25% black and 75% white
let lightGray = .black * 0.25 + .white * 0.75

// Make sky blue by lightening a combination of 25% blue and 75% cyan
let skyBlue = (.blue * 0.25 + .cyan * 0.75) * 0.25 + .white * 0.75

// Make dark red by combining 50% red and 50% black
let darkRed = .red * 0.50 + .black * 0.50

// Make purple from 60% blue and 40% red
let purple = (.blue * 0.60 + .red * 0.40)

// Then make lavender from 25% purple and 75% white
let lavender = purple * 0.25 + .white * 0.75

这篇关于在Swift中混合UIColors的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 23:47
查看更多