ios - 设置两种颜色的视图,如条形图不能快速工作
问题描述
我有一个关于自定义水平 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
}
}
}
解决方案
如果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
推荐阅读
- assembly - 我可以在汇编语言中使用注册变量作为被乘数吗?
- mysql - 我可以检查查询使用的是哪个连接 - laravel 读写连接吗?
- sql-server - 如何计算 SSRS 中的周转率 (%)?
- excel - 我需要从 1 日到当前日期的更新总和
- arrays - Flutter:如何发送一个数组来发布请求 API?
- excel - 每当另一行相同时,我如何每 5 行增加 1?
- java - 如何在保持抬头通知的情况下禁用通知声音?
- android - 在房间 DB Android 中删除表后数据未插入或更新
- visual-studio-code - 如何在vs代码中调试和运行c++
- python - 循环数据框,分组并保存转换后的值