Пользовательский вид прогресса на основе холста не округляется - PullRequest
0 голосов
/ 26 марта 2019

Я разработал пользовательский вид прогресса с помощью 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 Ответ

2 голосов
/ 26 марта 2019

Если percentage = 0, то leftIndicatorX должно быть равно rightCircleX - radius (чтобы левый и правый кружки совпадали). Попробуйте заменить

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

с

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

...