我有一个简单的CustomView,它绘制了3个垂直圆:
SimpleDrawingView.kt
class SimpleDrawingView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0) : View(context, attrs, defStyle) {
private val drawPaint: Paint = Paint()
init {
setupPaint()
}
private fun setupPaint() {
drawPaint.color = Color.RED
drawPaint.isAntiAlias = true
drawPaint.strokeWidth = 5f
drawPaint.style = Paint.Style.STROKE
drawPaint.strokeJoin = Paint.Join.ROUND
drawPaint.strokeCap = Paint.Cap.ROUND
}
override fun onDraw(canvas: Canvas?) {
canvas?.drawCircle(50f, 50f, 40f, drawPaint)
drawPaint.color = Color.BLUE
canvas?.drawCircle(50f, 150f, 40f, drawPaint)
drawPaint.color = Color.GREEN
canvas?.drawCircle(50f, 250f, 40f, drawPaint)
}
}
我将初始颜色设置为红色,然后使用onDraw()
方法更改颜色。但是它工作不正确,而是先绘制绿色圆圈而不是红色,为什么?
答案 0 :(得分:0)
这是自定义视图上使用@JvmOverloads
的问题。请按如下所示更改您的代码:
class SimpleDrawingView : View {
constructor(context: Context) : super(context) {
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
}
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(
context, attrs, defStyleAttr, defStyleRes
) {
}
private val drawPaint: Paint = Paint()
init {
setupPaint()
}
private fun setupPaint() {
drawPaint.color = Color.RED
drawPaint.isAntiAlias = true
drawPaint.strokeWidth = 5f
drawPaint.style = Paint.Style.STROKE
drawPaint.strokeJoin = Paint.Join.ROUND
drawPaint.strokeCap = Paint.Cap.ROUND
}
override fun onDraw(canvas: Canvas?) {
canvas?.drawCircle(50f, 50f, 40f, drawPaint)
drawPaint.color = Color.BLUE
canvas?.drawCircle(50f, 150f, 40f, drawPaint)
drawPaint.color = Color.GREEN
canvas?.drawCircle(50f, 250f, 40f, drawPaint)
}
}
输出如下: