我想在饼图中给出自定义颜色(使用图表窗格)。但是为此,setColors([NSUIColor])中的数组需要NSUIColor格式的颜色数组,并且我有颜色的十六进制代码。如何使用我的十六进制代码在饼图中实现自定义颜色?
我的代码功能:
func pieChartUpdate ()
{
//future home of pie chart code
let entry1 = PieChartDataEntry(value: Double(10), label: "Morning")
let entry2 = PieChartDataEntry(value: Double(20), label: "Evening")
let entry3 = PieChartDataEntry(value: Double(30), label: "Midday")
let entry4 = PieChartDataEntry(value: Double(40), label: "Before Bed")
let dataSet = PieChartDataSet(values: [entry1, entry2, entry3, entry4], label: "Widget Types")
let data = PieChartData(dataSet: dataSet)
pieChartTime.data = data
pieChartTime.chartDescription?.text = "Share of Widgets by Type"
//All other additions to this function will go here
dataSet.setColors(TimeColorString)
dataSet.valueColors = [UIColor.black]
//This must stay at end of function
pieChartTime.notifyDataSetChanged()
}
颜色代码数组:
let TimeColorString = [UIColor.init(hex: "3366cc"),UIColor.init(hex: "ff9900"),UIColor.init(hex: "dc3912"),UIColor.init(hex: "109618")]
我用来将Hexcode转换为UIColor的扩展名为:
//To convert hexcode into UI Color
extension UIColor {
convenience init(hex: String) {
let scanner = Scanner(string: hex)
scanner.scanLocation = 0
var rgbValue: UInt64 = 0
scanner.scanHexInt64(&rgbValue)
let r = (rgbValue & 0xff0000) >> 16
let g = (rgbValue & 0xff00) >> 8
let b = rgbValue & 0xff
self.init(
red: CGFloat(r) / 0xff,
green: CGFloat(g) / 0xff,
blue: CGFloat(b) / 0xff, alpha: 1
)
}
}
答案 0 :(得分:1)
设置如下颜色:
dataSet.colors = TimeColorString
如果你想使用setColors,下面是图表中的函数:
open func setColors(_ colors: [NSUIColor], alpha: CGFloat)
open func setColors(_ colors: NSUIColor...)
使用方法:
dataSet.setColors(TimeColorString, alpha: 1.0)
答案 1 :(得分:0)
首先创建NSUIColor数组,然后如下所示使用它:
let TimeColorString = [NSUIColor(cgColor: UIColor(hex: "#00a8e1").cgColor)]
dataSet.colors = TimeColorString