首页 > 解决方案 > 设置两种颜色的视图,如条形图不能快速工作

问题描述

我有一个关于自定义水平 barView 的问题。
我设置了颜色和值,但它没有向我显示两种颜色,它只显示一种颜色。
我不知道如何解决它。
而且,如果我想为索引 0 着色并且值索引 0 是左颜色,颜色索引 1 和值索引 1 是右颜色。对我有什么想法。
谢谢。

为什么给我看一种颜色。

 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
        }
    }
    }

标签: iosswiftcore-graphicsuigraphicscontext

解决方案


如果func draw你有一个错误,在ctx!.fill方法中你应该使用你的累积值作为原点 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

推荐阅读