Swift Charts绘制折线图+横坐标字体选中高亮

之前做的折线图功能,使用了比较流行的Charts框架,由于里面存在很多细节,简单做一下记录以免忘记(Demo在最后)

234

集成Charts框架

版本问题:最新版本是4.0.1 Release,但是实测下来折线图上的点击存在严重的bug,基本无法使用,不确定是不是因为Xcode12.4不兼容。万幸v4.0.0 没有问题,就采用这个版本了。

集成问题:其实集成本身没有什么困难的,官方提供了很多集成方式。困难的是我们公司规定直接用xcframework,所以需要自己打包成xcframework,使用官方集成方式的同学可以略过这一步。

下面是用到的命令

cd lottie-ios-3.1.8                               
rm -rf build
mkdir build

xcodebuild  -target Charts -configuration Release -sdk iphoneos ENABLE_BITCODE=YES BITCODE_GENERATION_MODE=bitcode ONLY_ACTIVE_ARCH=NO BUILD_DIR=build BUILD_ROOT=build clean build  

xcodebuild  -target Charts -configuration Debug -sdk iphonesimulator ENABLE_BITCODE=YES BITCODE_GENERATION_MODE=bitcode ONLY_ACTIVE_ARCH=NO BUILD_DIR=build BUILD_ROOT=build clean build 

rm -rf build/Charts.xcframework

xcodebuild -create-xcframework \
-framework build/Debug-iphonesimulator/Charts.framework \
-framework build/Release-iphoneos/Charts.framework \
-output build/Charts.xcframework

难点1:选中x轴文字高亮颜色

这个效果Charts本身并不支持,需要自定义XAxisRenderer来实现

https://stackoverflow.com/questions/54778065/ios-charts-highlight-specific-labels-on-x-axis-and-dashed-gridline-only-in-the-m

import Charts
import Foundation

class CreditScoreXAxisRenderer: XAxisRenderer {
    var selectedLabel: String?
    
    override func drawLabel(
        context: CGContext,
        formattedLabel: String,
        x: CGFloat, y: CGFloat,
        attributes: [NSAttributedString.Key: Any],
        constrainedTo size: CGSize,
        anchor: CGPoint,
        angleRadians: CGFloat
    ) {
        if formattedLabel == selectedLabel {
            var selectedAttributes = attributes
            selectedAttributes[.font] = UIFont.boldSystemFont(ofSize: 12)
            selectedAttributes[.foregroundColor] = UIColor.black
            
            super.drawLabel(context: context,
                            formattedLabel: formattedLabel,
                            x: x,
                            y: y,
                            attributes: selectedAttributes,
                            constrainedTo: size,
                            anchor: anchor,
                            angleRadians: angleRadians)
        } else {
            super.drawLabel(context: context,
                            formattedLabel: formattedLabel,
                            x: x,
                            y: y,
                            attributes: attributes,
                            constrainedTo: size,
                            anchor: anchor,
                            angleRadians: angleRadians)
        }
    }
}

难点2:选中的点变成实心圆点

试下来Charts本身属性不支持单独把数据点设置成实心,所以取巧在选中数据点上显示实心圆点的图片

// 将选中的数据点改成实心圆点图片
let chartDataSet = (chartView.data?.dataSets[0] as? LineChartDataSet)!
let values = chartDataSet.entries
values.forEach { entry in
    entry.icon = nil
}
entry.icon = UIImage(named: "circle_pointer")

难点3:双击选中数据的时候会自动取消选中效果的bug

class CreditScoreLineChartView: LineChartView {
    override func zoom(scaleX: CGFloat, scaleY: CGFloat, x: CGFloat, y: CGFloat) {}
}

主要代码:

struct Param {
    static var lineColor = UIColor(red: 0.161, green: 0.271, blue: 1, alpha: 1)
    static var hilightColor = lineColor.withAlphaComponent(0.03)
}

class ViewController: UIViewController, ChartViewDelegate {
    var chartView: CreditScoreLineChartView!
    let months: [String] = ["Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    
    // 所有点的颜色
    var circleColors: [UIColor] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        
        // 创建折线图组件对象
        chartView = CreditScoreLineChartView()
        chartView.frame = CGRect(x: 20, y: 300, width: view.bounds.width - 40, height: 270)
        
        chartView.delegate = self // 设置代理
        chartView.setScaleEnabled(false)
        
        chartView.leftAxis.axisMinimum = 300 // 左y轴数据最小值
        chartView.leftAxis.axisMaximum = 850 // 左y轴数据最大值
        chartView.leftAxis.granularity = 110 // 左y轴数据间隔
        chartView.leftAxis.setLabelCount(6, force: true) // 左y轴有几个label
        chartView.xAxis.drawAxisLineEnabled = false // 竖向网格线
        chartView.xAxis.axisMinimum = -0.2 // 设置x轴最小值,使左边多一点空间
        chartView.xAxis.axisMaximum = 5.2 // 设置x轴最大值,使右边多一点空间
        
        let ll1 = ChartLimitLine(limit: 800, label: " ")
        ll1.lineWidth = 1
        ll1.lineColor = UIColor(red: 0, green: 0.698, blue: 0.294, alpha: 1)
        ll1.lineDashLengths = [3, 2]
        ll1.labelPosition = .rightTop
        ll1.valueFont = .systemFont(ofSize: 10)
        
        let ll2 = ChartLimitLine(limit: 650, label: " ")
        ll2.lineColor = UIColor(red: 0.3, green: 0.3, blue: 0.3, alpha: 1)
        ll2.lineWidth = 1
        ll2.lineDashLengths = [3, 2]
        ll2.labelPosition = .rightBottom
        ll2.valueFont = .systemFont(ofSize: 10)
        
        chartView.leftAxis.addLimitLine(ll1)
        chartView.leftAxis.addLimitLine(ll2)
        
        // 网格只显示竖线
        chartView.chartDescription.enabled = false
        chartView.leftAxis.drawGridLinesEnabled = false
        chartView.leftAxis.drawAxisLineEnabled = false
        // 网格只显示竖线
        chartView.rightAxis.enabled = false
        
        chartView.xAxis.labelPosition = .bottom
        chartView.legend.enabled = false
        
        view.addSubview(chartView)
        
        chartView.xAxis.granularity = 1 // 间隔尺寸,粒度
        chartView.xAxis.labelCount = months.count // x轴标题数量
        chartView.xAxis.labelFont = UIFont.systemFont(ofSize: 12)
        chartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: months)
        chartView.xAxis.labelTextColor = .lightGray
        chartView.xAxis.gridColor = UIColor(red: 0.898, green: 0.898, blue: 0.898, alpha: 1) // x轴网格线颜色
        
        // 生成随机数据
        var dataEntries = [ChartDataEntry]()
        let values: [Double] = [500, 530, 520, 500, 530, 560]
        for (i, value) in values.enumerated() {
            let entry = ChartDataEntry(x: Double(i), y: value)
            dataEntries.append(entry)
        }
        
        let chartDataSet = LineChartDataSet(entries: dataEntries, label: "图例1")
        // 目前折线图只包括1根折线
        let chartData = LineChartData(dataSets: [chartDataSet])
        
        // 设置折点颜色
        chartDataSet.setColor(Param.lineColor) // 线颜色
        chartDataSet.drawIconsEnabled = true // 允许绘制图片
        chartDataSet.circleRadius = 4 // 数据点半径
        chartDataSet.circleHoleRadius = 2 // 数据点孔半径
        chartDataSet.lineWidth = 2 // 线宽
        chartDataSet.drawValuesEnabled = false
        
        chartDataSet.setCircleColor(Param.lineColor) // 圆圈颜色
        chartDataSet.highlightColor = Param.hilightColor // 十字线颜色
        chartDataSet.highlightLineWidth = 20 // 十字线线宽
        chartDataSet.drawHorizontalHighlightIndicatorEnabled = false // 不显示横向十字线
        
        // 设置折现图数据
        chartView.data = chartData
        chartView.xAxisRenderer = CreditScoreXAxisRenderer(viewPortHandler: chartView.viewPortHandler, axis: chartView.xAxis, transformer: chartView.getTransformer(forAxis: .left))
        
        chartView.highlightValue(x: 5, dataSetIndex: 0)
    }
    
    // 折线上的点选中回调
    func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
        let selectLabel = months[Int(entry.x)]
        (self.chartView.xAxisRenderer as! CreditScoreXAxisRenderer).selectedLabel = selectLabel
        
        // 将选中的数据点改成实心圆点图片
        let chartDataSet = (chartView.data?.dataSets[0] as? LineChartDataSet)!
        let values = chartDataSet.entries
        values.forEach { entry in
            entry.icon = nil
        }
        entry.icon = UIImage(named: "circle_pointer")
        
        // 重新渲染表格
        chartView.data?.notifyDataChanged()
        chartView.notifyDataSetChanged()
    }
}

Demo地址:LineChartsDemo

你可能感兴趣的:(Swift Charts绘制折线图+横坐标字体选中高亮)