在SurfaceView上渲染位图会影响性能

时间:2013-02-14 08:23:02

标签: android bitmap render android-canvas surfaceview

我有一个扩展SurfaceView(Android应用程序API级别8)的活动。需要将位图绘制到背景而不是简单的颜色。我能够在画布上绘制位图 - >使用void render(Canvas canvas)中的注释代码,但它会使性能太低。

如果我们使用位图,渲染会变慢,但是如果我们只绘制颜色,那么一切都很好。

代码有问题吗?如何在不影响性能的情况下设置背景图像?

public class MainGamePanel extends SurfaceView implements
        SurfaceHolder.Callback {
public void render(Canvas canvas) {


        canvas.drawColor(Color.WHITE);
        /*
        Rect dest = new Rect(0, 0, getWidth(), getHeight());
        Paint paint = new Paint();
        paint.setFilterBitmap(true);

        Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.background_play);
        canvas.drawBitmap(myBitmap, null, dest, paint);
        */
        droid.draw(canvas);
    }
}

1 个答案:

答案 0 :(得分:2)

也许你应该将你的Bitmap创建为一个字段并在你的render方法()之外解码它,如:

public class MainGamePanel extends SurfaceView implements
    SurfaceHolder.Callback {

    private Bitmap myBitmap; //creating a field

    public MainGamePanel() {

        myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.background_play); //decode bitmap in constructor

    }

    public void render(Canvas canvas) {


    canvas.drawColor(Color.WHITE);

    Rect dest = new Rect(0, 0, getWidth(), getHeight());
    Paint paint = new Paint();
    paint.setFilterBitmap(true);

    canvas.drawBitmap(myBitmap, null, dest, paint); //draw your bitmap

    droid.draw(canvas);
    }
}