前言
最近在项目中需要实现一个简单的横向柱状图(如下图),需要实现在左边名字之后显示对应进度,同时进度之后需要跟上当前进度的内容。由于太菜找不到好的实现方法,于是决定使用自定义View实现。
实现
ps:这里我采取了一个偷懒的办法,只实现单个数据的柱状图,然后结合RecyclerView展示多个数据,同时还支持滑动,方便了不少。
单个柱状图比较简单,从左到右依次绘制标题、灰色条、进度条以及当前进度的内容。
初始化
private var titlePaint = Paint() //标题画笔
private var grayPaint = Paint() //灰色条画笔
private var progressPaint = Paint() //进度条画笔
private var contentPaint = Paint() //内容画笔
private var titleColor = TITLE_COLOR //对应颜色
private var grayColor = Color.GRAY
private var progressColor = PROGRESS_COLOR
private var contentColor = CONTENT_COLOR
private var title = "" //标题
private var content = "" //内容
private var maxHeight = 0f //最大高度
private var totalProgressWidth = dp2px(TOTAL_PROGRESS_WIDTH)
private var grayHeight = dp2px(GRAY_HEIGHT)
private var titleMargin = 0f
private var titleHeight = 0f
private var contentHeight = 0f
private var currX = 0f //当前绘制x坐标
private var progress = 0
private var progressWidth = 0f
private var grayWidth = 0f
private var progressHeight = 0f
init {
initPaint()
initWidthAndHeight()
}
private fun initPaint(){
titlePaint.isAntiAlias = true
titlePaint.style = Paint.Style.FILL_AND_STROKE
titlePaint.color = titleColor
titlePaint.textSize = sp2px(TITLE_SIZE_DEFAULT)
grayPaint.isAntiAlias = true
grayPaint.color = grayColor
grayPaint.style = Paint.Style.FILL_AND_STROKE
progressPaint.isAntiAlias = true
progressPaint.color = progressColor
progressPaint.style = Paint.Style.FILL_AND_STROKE
contentPaint.isAntiAlias = true
contentPaint.color = contentColor
contentPaint.style = Pai