您可以對顏色的rgb值使用數學運算。
要獲得rgb值,您可以使用getRed:green:blue:alpha
方法UIColor
。然後,您所要做的就是根據您需要多少部分將顏色進行平均。
這是一個函數,它應該根據開始和結束顏色以及您需要多少個分區來返回一組顏色。
解決方案
func divideColors(firstColor: UIColor, secondColor: UIColor, sections: Int) -> [UIColor] {
// get rgb values from the colors
var firstRed: CGFloat = 0; var firstGreen: CGFloat = 0; var firstBlue: CGFloat = 0; var firstAlpha: CGFloat = 0;
firstColor.getRed(&firstRed, green: &firstGreen, blue: &firstBlue, alpha: &firstAlpha)
var secondRed: CGFloat = 0; var secondGreen: CGFloat = 0; var secondBlue: CGFloat = 0; var secondAlpha: CGFloat = 0;
secondColor.getRed(&secondRed, green: &secondGreen, blue: &secondBlue, alpha: &secondAlpha)
// function to mix the colors
func mix(_ first: CGFloat, _ second: CGFloat, ratio: CGFloat) -> CGFloat { return first + ratio * (second - first) }
// variable setup
var colors = [UIColor]()
let ratioPerSection = 1.0/CGFloat(sections)
// mix the colors for each section
for section in 0 ..< sections {
let newRed = mix(firstRed, secondRed, ratio: ratioPerSection * CGFloat(section))
let newGreen = mix(firstGreen, secondGreen, ratio: ratioPerSection * CGFloat(section))
let newBlue = mix(firstBlue, secondBlue, ratio: ratioPerSection * CGFloat(section))
let newAlpha = mix(firstAlpha, secondAlpha, ratio: ratioPerSection * CGFloat(section))
let newColor = UIColor(red: newRed, green: newGreen, blue: newBlue, alpha: newAlpha)
colors.append(newColor)
}
return colors
}
你的問題被標記爲Objective-C
,但它應該是很容易的雨燕代碼轉換上面的Objective-C,因爲你會使用相同的UIColor
API。
下面是測試上述功能的一些代碼(適用於Swift操場)。
測試代碼
let sections = 5
let view = UIView(frame: CGRect(x: 0, y: 0, width: 250, height: 50))
for (index, color) in divideColors(firstColor: UIColor.purple, secondColor: UIColor.orange, sections: sections).enumerated() {
let v = UIView(frame: CGRect(x: CGFloat(index) * 250/CGFloat(sections), y: 0, width: 250/CGFloat(sections), height: 50))
v.backgroundColor = color
view.addSubview(v)
}
view.backgroundColor = .white
測試結果
它也適用於任何數量的部分和不同顏色的!
如果只有你可以發佈這在Objective-c。 – Vulkan
@Vulkan無論使用Swift還是Objective-C,API和邏輯都是一樣的。現有的SO答案涵蓋了如何做所有這些事情(從'UIColor'獲得RGB值,創建和修改數組等等) – nathan
你是對的,但我無法讀Swift,我讀了這些:「firstColor。 getRed(&firstRed,green:&firstGreen,blue:&firstBlue,alpha:&firstAlpha)「,」func mix(_ first:CGFloat,_ second:CGFloat,ratio:CGFloat) - > CGFloat {return first + ratio *(second - first) }」。我無法讀取它們,也無法將它們轉換爲ObjC。 – Vulkan