Search code examples
iosswiftcore-graphicsuigraphicscontext

Set two colors of view like bars doesn't works by swift


I have a question about custom horizontal barView.
I set color & value, but it doesn't show two color to me, and it just show one color.
I don't know how to fix it.
And, if I want to colors index 0 and values index 0 is left color, colors index 1 and values index 1 is right color. Have any idea to me.
Thanks.

why show me one color.

 import SnapKit

    class MyAssetView: UIView {

    let barView: BarView = { () -> BarView in
        let ui = BarView()
        ui.colors = [UIColor.blue, UIColor.red]
        ui.values = [0.2, 0.8]
        return ui
    }()


    override init(frame: CGRect = CGRect.zero) {
        super.init(frame: frame)

        self.setupView()
    }

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


    func setupView(){

        self.addSubview(barView)

        barView.snp.makeConstraints { (make) in
            make.top.equalTo(10)
            make.left.equalTo(30)
            make.height.equalTo(30)
            make.right.equalTo(-30)
        }
    }

    }

    class BarView : UIView {

    var colors : [UIColor] = [UIColor]() {
        didSet {
            self.setNeedsDisplay()
        }
    }

    var values : [CGFloat] = [CGFloat]() {
        didSet {
            self.setNeedsDisplay()
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.clear
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func draw(_ rect: CGRect) {

        let r = self.bounds // the view's bounds
        let numberOfSegments = values.count // number of segments to render

        let ctx = UIGraphicsGetCurrentContext() // get the current context

        var cumulativeValue:CGFloat = 0 // store a cumulative value in order to start each line after the last one
        for i in 0..<numberOfSegments {

            ctx!.setFillColor(colors[i].cgColor) // set fill color to the given color if it's provided, else use clearColor
            ctx!.fill(CGRect(x: 0, y: 0, width: values[i]*r.size.width, height: r.size.height)) // fill that given segment

            cumulativeValue += values[i] // increment cumulative value
        }
    }
    }

Solution

  • In func draw you have an error , in ctx!.fill method you should use your cumulativeValue as origin X.

    ctx!.fill(CGRect(x: cumulativeValue*r.size.width, y: 0, width: values[i]*r.size.width, height: r.size.height)) // fill that given segment