android - 基于画布的自定义进度视图不圆
问题描述
我已经使用 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
thenleftIndicatorX
必须等于rightCircleX - radius
(使左右圆重合)。尝试更换
val leftIndicatorX = width - (width * percentage) / 100
和
val leftIndicatorX = rightCircleX - radius - (rightCircleX - leftCircleX) * percentage / 100
推荐阅读
- laravel - 使用 Laravel 进行自动化测试
- javascript - 在 firebaseRef.on 监听器中等待异步值
- mysql - 当我在两个表上执行“选择”查询时,它会呈现表内的所有元素
- python - Plotly 桑基图 Python
- javascript - OPTIONS 请求得到“401 Unauthorized”响应
- ios - 加载应用程序以存储“无法识别的区域设置”时发出警告
- c++ - QtService:在Windows10上启动安装的Service
- javascript - router.delete 返回空数组
- c++ - 在 C 中指定小数点后的值应该可以更改
- javascript - 通过 Jquery (localStorage) 记住颜色选择