使用着色器在画布上绘制多条线会导致性能问题

时间:2016-07-04 13:36:46

标签: android performance android-canvas

在SurfaceView中的一个单独的线程中,我使用Paint绘制了~50条贝塞尔曲线,之前已设置为具有如下代码中的渐变:

LinearGradient gradient = new LinearGradient(0, 0, 0, height, Color.BLACK, Color.WHITE, Shader.TileMode.MIRROR); paint.setShader(gradient);

将着色器设置为绘制会导致严重的性能问题 - 视图开始滞后。但是,如果我只是注释掉设置着色器来绘制它的效果非常好,那么问题肯定在渐变中。

线程代码:

private class DrawingRunnable implements Runnable {

    private final SurfaceHolder surfaceHolder;
    private final MyView surfaceView;

    public DrawingRunnable(SurfaceHolder surfaceHolder, MyView surfaceView) {
        this.surfaceHolder = surfaceHolder;
        this.surfaceView = surfaceView;
    }

    @Override
    public void run() {
        while (isRunning) {

            Canvas canvas = null;
            try {
                canvas = surfaceHolder.lockCanvas(null);

                if (canvas != null) {
                    canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
                    synchronized (surfaceHolder) {
                        surfaceView.drawMyHeavyView(canvas);
                    }
                }
            } catch (Throwable e) {
                Timber.w(e, "Error occurred while drawing surface view");
            } finally {
                if (canvas != null) {
                    surfaceHolder.unlockCanvasAndPost(canvas);
                }
            }
        }
    }
}

在画布上绘图:

protected void drawMyHeavyView(Canvas canvas) {

    for (int index = 0; index < 50; index++) {

        path.reset();
        path.moveTo(x1, y1);

        modifySomeAmplitudeRandomValues(index);

        path.quadTo(x3, amplitude[index], x2, y2);

        canvas.drawPath(path, paint);
    }
}

您应该假设那些未知的参数(例如x1,y1,x2等)是视图业务逻辑的一部分,并且对于当前的讨论并不具有价值。

你能告诉我哪里错了吗?

P.S。:我没有在onDraw上分配LinearGradient。

0 个答案:

没有答案