SurfaceView和View之间的绘制画布行为不同吗?

时间:2018-07-24 14:00:19

标签: android canvas surfaceview

我有一个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

enter image description here

为什么SurfaceViewView之间的绘制画布行为不同,SurfaceView上有粘性,而View上的每个循环都被清除了?

0 个答案:

没有答案