首页 > 解决方案 > 基于画布的自定义进度视图不圆

问题描述

我已经使用 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()
  }
}

标签: androidandroid-layoutkotlinandroid-canvas

解决方案


如果percentage = 0thenleftIndicatorX必须等于rightCircleX - radius(使左右圆重合)。尝试更换

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

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


推荐阅读