IOS 自定义折线图[swift]

OC版:https://www.jianshu.com/p/fefe89b322f2

预览

IOS 自定义折线图[swift]_第1张图片
折线图

变量初始化

var array: NSArray
    let borderX: CGFloat
    let borderY: CGFloat
    let x: Int
    let y: Int
    let yValue: CGFloat
    let xValue: CGFloat
    let yStart: CGFloat
    let xStart: CGFloat
    let widthX: CGFloat
    let heightY: CGFloat

构造函数

init(frame:CGRect,array:NSArray) {
        //内边距
        borderX = 40
        borderY = 20
        //x和y的个数
        //x = 4: 2014,2015,2016,2017
        //y = 6: 0,500,100,1500,2000,2500
        x = 4
        y = 6
        //x和y每个单位代表的值
        yValue = 500
        xValue = 1
        //x和y的起始值
        yStart = 0
        xStart = 2014
        //x和y的单位长度
        widthX = (frame.size.width - borderX * 2) / CGFloat(x)
        heightY = (frame.size.height - borderY * 2) / CGFloat(y)
        self.array = array
        super.init(frame: frame)
        self.frame = frame
        self.backgroundColor = UIColor.clear
        //画x轴的label:2014,2015...
        drawX()
        //画y轴的label:0,500,1000...
        drawY()
        //画折线
        drawline()
    }

required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

画坐标轴,虚线,和数据点

override func draw(_ rect: CGRect) {
        //画坐标轴
        let context = UIGraphicsGetCurrentContext()
        context?.setStrokeColor(UIColor.blue.cgColor)
        context?.setLineWidth(1)
        context?.move(to: CGPoint(x: borderX, y: borderY))
        context?.addLine(to: CGPoint(x: borderX, y: rect.size.height - borderY))
        context?.addLine(to: CGPoint(x: rect.size.width - borderX, y: rect.size.height - borderY))
        context?.strokePath()
        //画y轴的分割虚线
        let context2 = UIGraphicsGetCurrentContext()
        context2?.setStrokeColor(UIColor.lightGray.cgColor)
        context2?.setLineWidth(1)
        for i in 1..

写X轴Y轴的数字

func drawX() {
        for i in 0..

画折线

func drawline() {
        
        let yTotalValue = yStart + yValue * CGFloat(y)
        let height = self.frame.size.height - borderY * CGFloat(2)
        let pointy = self.frame.size.height - (self.array[0] as! CGFloat)/yTotalValue*height - borderY
         //在第一个点下方写数值
        let textLabel = UILabel(frame: CGRect(x: widthX/2+borderX, y: pointy, width: 50, height: 20))
        textLabel.text = String.init(format: "%i", (self.array[0] as! Int))
        textLabel.font = UIFont.systemFont(ofSize: 10)
        self.addSubview(textLabel)
        //贝塞尔曲线设置起始点
        let linePath = UIBezierPath()
        linePath.move(to: CGPoint(x: widthX/2+borderX, y: pointy))
        //开始画折线和后续的数值
        for i in 0..

使用

 let array: NSArray = [1342,2123,1654,1795];
        let chartView = ChartView(frame: CGRect(x: 0, y: 70, width: 320, height: 250), array: array);
        self.view.addSubview(chartView)

你可能感兴趣的:(IOS 自定义折线图[swift])