android 圆环进度view
新建RoundProgressBar
class RoundProgressBar : View { private val paint = Paint() var max = 100 //最大进度 var progress = 0 //当前进度 取值范围 0-max set(value) { field = value invalidate()//调用该方法后 onDraw会执行 } var roundColor = Color.GRAY //圆环颜色 var roundProgressColor = Color.YELLOW //圆环进度的颜色 var roundWidth:Float = 16f //圆环的宽度(粗细) constructor(context: Context) : super(context) { init(null, 0) } constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) { init(attributeSet, 0) } constructor(context: Context, attributeSet: AttributeSet, defStyle: Int) : super(context, attributeSet, defStyle) { init(attributeSet, defStyle) } private fun init(attributeSet: AttributeSet?, defStyle: Int) { val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.RoundProgressBar, defStyle, 0) max = typedArray.getInt(R.styleable.RoundProgressBar_max, 100) progress = typedArray.getInt(R.styleable.RoundProgressBar_progress, 30) progress = max(0,min(progress,100)) roundColor = typedArray.getColor(R.styleable.RoundProgressBar_roundColor, Color.GRAY) roundProgressColor = typedArray.getColor(R.styleable.RoundProgressBar_roundProgressColor,Color.YELLOW) roundWidth = typedArray.getDimension(R.styleable.RoundProgressBar_roundWidth,16f) typedArray.recycle() } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) // 获取圆心x坐标 (x=y) val c = (width / 2).toFloat() // 圆环的半径 val radius = c - roundWidth / 2 paint.color = roundColor //设置颜色 paint.style = Paint.Style.STROKE paint.strokeWidth = roundWidth //设置宽度 paint.isAntiAlias = true //消除锯齿 canvas?.drawCircle(c,c,radius,paint) paint.color = roundProgressColor paint.style = Paint.Style.STROKE paint.strokeWidth = roundWidth paint.isAntiAlias = true val rectF = RectF(c - radius,c - radius,c + radius,c + radius) canvas?.drawArc(rectF,(-90).toFloat(),(progress * 360 / max).toFloat(),false,paint) //invalidate() } }
context.obtainStyledAttributes 用来获取布局文件的所有属性
canvas?.drawCircle(c,c,radius,paint) 根据画笔类型画圆环或者画圆
Paint.Style.STROKE 画圆环 Paint.Style.FILL 画圆 Paint.Style.FILL_AND_STROKE 画圆 直径包括strokeWidth宽度
canvas?.drawArc(矩形对象,起始角度,画的角度,是否包含圆心,paint) 想要包含圆心的 画笔样式不能是Paint.Style.STROKE 才有效果
在res.values下创建attrs.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="RoundProgressBar"> <attr name="max" format="integer" /> <attr name="progress" format="integer" /> <attr name="roundColor" format="color" /> <attr name="roundProgressColor" format="color" /> <attr name="roundWidth" format="dimension" /> </declare-styleable> </resources>
后面就可以使用了
<com.chao.myvideo.view.RoundProgressBar android:layout_width="50dp" android:layout_height="50dp" app:progress="0" app:max="100" android:layout_gravity="center"/>