我有一个SurfaceView
如下
class CanvasDrawView : SurfaceView, SurfaceHolder.Callback {
@JvmOverloads
constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0)
: super(context, attrs, defStyleAttr)
init {
holder.addCallback(this)
}
private val strokePaint = Paint()
.apply { color = Color.RED }
.apply { strokeWidth = 16f }
private var job: Job? = null
override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {
// Do nothing for now
}
override fun surfaceDestroyed(holder: SurfaceHolder?) {
job?.cancel()
}
override fun surfaceCreated(holder: SurfaceHolder?) {
var i = 0f
job = launch {
while (true) {
val canvas = holder?.lockCanvas(null)
synchronized(holder!!) {
i += 1f
if (i > width) {
i = 0f
}
canvas?.drawPoint(i, 50f, strokePaint)
}
holder?.unlockCanvasAndPost(canvas)
}
}
}
}
还有一个View
具有相同的动画图形。
class CustomDrawView : View {
@JvmOverloads
constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0)
: super(context, attrs, defStyleAttr)
private val strokePaint = Paint()
.apply { color = Color.RED }
.apply { strokeWidth = 16f }
private var i = 0f
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
i += 1f
if (i > width) {
i = 0f
}
canvas?.drawPoint(i, 50f, strokePaint)
invalidate()
}
}
在画布上绘制时,SurfaceView
绘制的画布保留在画布上,但是View
绘制的画布已清除,需要重新绘制,如下面的gif所示(第一个浮点是来自View
,第二行(通过绘制点形成)来自SurfaceView
为什么SurfaceView
和View
之间的绘制画布行为不同,SurfaceView
上有粘性,而View
上的每个循环都被清除了?