/**
* Created by yangxy on 2018/9/28.
*/
class CircleStudyBar @JvmOverloads constructor(
private var mContext: Context, private var attrs: AttributeSet? = null, private var defStyleAttr: Int = 0) : View(mContext, attrs, defStyleAttr) {
private var totalPaint: Paint? = null
private var progressPaint: Paint? = null
private var mWidth: Float = 0f
private var mHeight: Float = 0f
private var rectF: RectF? = null
private var progress: Float = 0f
private var targetProgress: Float = 0f
private var totalColor: Int = 0
private var progressColor: Int = 0
init {
initAttrs()
initPaint()
}
private fun initAttrs() {
val typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.CircleStudyBar)
totalColor = typedArray.getColor(R.styleable.CircleStudyBar_totalBgColor, resources.getColor(R.color.color_value_1a000000))
progressColor = typedArray.getColor(R.styleable.CircleStudyBar_progressColor, resources.getColor(R.color.color_value_ff7767))
typedArray.recycle()
}
private fun initPaint() {
totalPaint = Paint(Paint.ANTI_ALIAS_FLAG)
totalPaint?.strokeWidth = Utils.dip2px(context, 3f)
totalPaint?.color = totalColor
totalPaint?.style = Paint.Style.STROKE
progressPaint = Paint(Paint.ANTI_ALIAS_FLAG)
progressPaint?.strokeWidth = Utils.dip2px(context, 3f)
progressPaint?.color = progressColor
progressPaint?.style = Paint.Style.STROKE
progressPaint?.strokeCap = Paint.Cap.ROUND
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
mWidth = measuredWidth.toFloat()
mHeight = measuredHeight.toFloat()
rectF = RectF(Utils.dip2px(context, 6f),
Utils.dip2px(context, 6f),
mWidth - Utils.dip2px(context, 6f),
mHeight - Utils.dip2px(context, 6f))
drawTotalCircle(canvas)
drawProgressCircle(canvas)
}
/**
* 画总的背景圆
*/
private fun drawTotalCircle(canvas: Canvas?) {
canvas?.drawArc(rectF, 0f, 360f, false, totalPaint)
}
/**
* 画进度条的圆
*/
private fun drawProgressCircle(canvas: Canvas?) {
canvas?.drawArc(rectF, -90f, 360f * progress, false, progressPaint)
}
private fun setProgress(progress: Float) {
this.progress = progress
postInvalidate()
}
fun startAnimate(currentCourse: Int, totalCourse: Int) {
this.targetProgress = currentCourse.toFloat() / totalCourse
val animator = ValueAnimator.ofObject(FloatEvaluator(), 0, targetProgress)
animator.addUpdateListener {
val value: Float = it.animatedValue.toString().toFloat()
setProgress(value)
}
animator.interpolator = LinearInterpolator()
animator.duration = 2000
animator.start()
}
}
网友评论