基于画布的自定义进度视图无法显示

时间:2019-03-26 07:01:41

标签: android android-layout kotlin android-canvas

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

enter image description here

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()
  }
}

1 个答案:

答案 0 :(得分:2)

如果Product,则percentage = 0必须等于leftIndicatorX(以便左右两个圆圈重合)。尝试更换

rightCircleX - radius

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