Charts是一个强大的图表框架,MPAndroidChart 在 iOS 上的移植。可以绘制线形图,直方图,饼状图等等。(由于在项目中只做了饼状图,这里就只有饼状图的代码了,其它的图基本上用法类似)
更新:适配3.0版本
首先需要import Charts
绘制饼状图:
var viewPie: PieChartView!
创建饼状图:
func initChart () {
// 基本样式
viewPie?.setExtraOffsets(left: 0, top: 0, right: 0, bottom: 0) //饼状图距离边缘的间隙
viewPie?.usePercentValuesEnabled = false //是否根据所提供的数据, 将显示数据转换为百分比格式
viewPie?.dragDecelerationEnabled = false //拖拽饼状图后是否有惯性效果
viewPie?.drawSliceTextEnabled = false //是否显示区块文本
// 空心圆样式
viewPie?.drawHoleEnabled = true //饼状图是否是空心
viewPie?.rotationEnabled = false // 旋转指示
viewPie?.descriptionText = "" // 文本内容
viewPie?.holeRadiusPercent = 0.5 //空心半径占比
viewPie.holeColor = UIColor.clearColor() //中心颜色
viewPie?.transparentCircleRadiusPercent = 0.6 //半透明空心半径占比
viewPie.drawCenterTextEnabled = true //中心的文本启用
}
没有数据时饼状图的状态:
func setChartDataEmpty() {
var yValues:[BarChartDataEntry] = []
let entryValue = BarChartDataEntry.init(x: 0, yValues: [Double(1)])
yValues.append(entryValue)
let dataSet = PieChartDataSet.init(yVals: yValues, label: "")
dataSet.drawValuesEnabled = false
dataSet.selectionShift = 0
dataSet.valueLineVariableLength = false
var colors: [UIColor] = []
colors.append(UIColor.init(hexValue: "c0c0c0"))
dataSet.colors = colors
let data = PieChartData.init(xVals: xValues, dataSet:dataSet)
viewPie?.data = data
}
填充数据:
// 动画效果
func doAnimate() -> Void {
viewPie?.animate(xAxisDuration: 1, easingOption: ChartEasingOption.EaseOutSine)
}
func setChartData() {
doAnimate()
//此处填入展示的相应数字
let value1 = Double(1)
let value2= Double(1)
if value1 + value2 == 0 {
setChartDataEmpty()
return
}
let xValues:[String] = []
var yValues:[ChartDataEntry] = []
let entryValue1 = BarChartDataEntry.init(x: 1, yValues: [value1])
let entryValue2 = BarChartDataEntry.init(x: 2, yValues: [value2] )
yValues.append(entryValue1)
yValues.append(entryValue2)
let dataSet = PieChartDataSet.init(yVals: yValues, label: "")
dataSet.drawValuesEnabled = false
dataSet.selectionShift = 0
dataSet.valueLineVariableLength = false
var colors: [UIColor] = []
colors.append(UIColor.init(hexValue: "eb9837"))
colors.append(UIColor.init(hexValue: "90c549"))
dataSet.colors = colors
let data = PieChartData.init(xVals: xValues, dataSet: dataSet)
viewPie?.data = data
}