2022-07-25 简单绘制扇形进度条

1.效果图如下(外圈效果):

image.png

2.源代码如下:

import android.content.Context
import android.graphics.*
import android.text.TextPaint
import android.util.AttributeSet
import android.view.View
import com.rdc.module_member.ext.dp2px
class RoundLevelView @kotlin.jvm.JvmOverloads constructor(
  context: Context,
  attrs: AttributeSet? = null,
  defStyleAttr: Int = 0,
  defStyleRes: Int = 0
) : View(context, attrs, defStyleAttr, defStyleRes) {
  //
  //文字画笔
  private var mPaint = TextPaint(Paint.ANTI_ALIAS_FLAG) //抗锯齿

  //背景色
  private val mNormalColor = Color.parseColor("#999999")

  //进度颜色
  private val mProgressColor = Color.parseColor("#C62430")

  //最高等级
  private var mMaxLevel = 10

  //当前等级
  private var mCurrentLevel = 0
  //

  //
  init {
    mPaint.strokeWidth = 1.dp2px() * 1f
    mPaint.style = Paint.Style.STROKE
    mPaint.strokeCap = Paint.Cap.ROUND//作用于圆环结尾
  }
  //

  //
  private var mRectF = RectF()
  override fun onDraw(canvas: Canvas?) {
    super.onDraw(canvas)
    if (width <= 0 || height <= 0) return
    canvas?.let { c ->
      val radius = width.coerceAtMost(height) / 2f - mPaint.strokeWidth / 2f
      mPaint.color = mNormalColor
      c.drawCircle(width / 2f, height / 2f, radius, mPaint)
      mPaint.color = mProgressColor
      mRectF.left = width / 2f - radius // 左上角x
      mRectF.top = height / 2f - radius// 左上角y
      mRectF.right = width / 2f + radius  // 左下角x
      mRectF.bottom = height / 2f + radius// 右下角y
      c.drawArc(mRectF, -90f, (mCurrentLevel * 1f / mMaxLevel) * 360, false, mPaint)
    }
  }
  //

  //
  fun setLevel(currentLevel: Int, maxLevel: Int = 10) {
    mMaxLevel = maxLevel
    mCurrentLevel = currentLevel
    postInvalidate()
  }
  //
}

你可能感兴趣的:(2022-07-25 简单绘制扇形进度条)