Canvas 基于自定义进度视图不圆

Canvas based custom progress view doesn't get round

我使用 android canvas 开发了自定义进度视图。目前我面临一个问题,如果进度值低于 3,它不会像图像中那样使边缘变圆。5% 到 100% 都很好。以下是我的代码。我也附上了图片希望有人能帮忙。

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.support.v4.content.ContextCompat
import android.util.AttributeSet
import android.view.View

class DevProgressIndicator @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
  View(context, attrs, defStyleAttr) {
  private var color: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
  private var bgColor: Paint = Paint(Paint.ANTI_ALIAS_FLAG)

  var percentage = 0f
    set(value) {
      if (value in 0f..100f) field = value
      else throw IllegalArgumentException("Value should be more than 0 and less or equal 100")
    }

  init {
    color.apply {
      color = Color.RED
      style = Paint.Style.FILL
    }
    bgColor.apply {
      color = ContextCompat.getColor(context, R.color.material_grey_100)
      style = Paint.Style.FILL
    }
  }

  override fun onDraw(canvas: Canvas?) {
    super.onDraw(canvas)
    if (canvas == null) {
      return
    }
    val centerY = (height / 2).toFloat()
    val radius = centerY
    val leftCircleX = radius
    val rightCircleX = width - radius
    canvas.drawCircle(leftCircleX, centerY, radius, bgColor)
    canvas.drawCircle(rightCircleX, centerY, radius, bgColor)
    canvas.drawRect(leftCircleX, 0f, rightCircleX, height.toFloat(), bgColor)
    if (percentage == 0f) {
      return
    }
    val leftIndicatorX = width - (width * percentage) / 100
    canvas.drawCircle(rightCircleX, centerY, radius, color)
    canvas.drawCircle(leftIndicatorX + radius, centerY, radius, color)
    canvas.drawRect(leftIndicatorX + radius, 0f, rightCircleX, height.toFloat(), color)
  }

  fun setColor(colorId: Int) {
    color.color = ContextCompat.getColor(context, colorId)
    invalidate()
    requestLayout()
  }
}

如果percentage = 0那么leftIndicatorX必须等于rightCircleX - radius(这样左右圆圈重合)。尝试替换

val leftIndicatorX = width - (width * percentage) / 100

val leftIndicatorX = rightCircleX - radius - (rightCircleX - leftCircleX) * percentage / 100