4

我正在使用 Android 2.2 构建游戏。主游戏Activity使用自定义SurfaceView

class GameView extends SurfaceView

据我了解,该onDraw()方法需要执行自己的线程。考虑到这一点,我打算在以下位置添加背景图像onDraw()

canvas.drawBitmap(wallpaper, 0, 0, paint);
paint = new Paint();

但是当我执行游戏时,它变得非常慢。如果我注释掉这new Paint()条线,游戏就会加速。

是我做错了什么,还是有解决我的问题的方法?例如,有没有办法减少调用次数onDraw()?或者XML向我的自定义SurfaceView类添加一个属性?

这是我如何加载可绘制图像的代码。


public Bitmap loadBitmap(String image) {
        Bitmap bitmap = null;

        try {
            int id = R.drawable.class.getField(image).getInt(new Integer(0));
            bitmap = BitmapFactory.decodeResource(context.getResources(), id);
//          bitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.RGB_565); 
        } catch(Exception ex) {
            Log.e("loadBitmap", ex.getMessage());
        }

        return bitmap;
    }

这是该onDraw方法的代码。不幸的是,我无法发布所有内容。

paint.setColor(Color.BLACK);
canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
canvas.drawBitmap(gameLevel.getBitmap(), 0, 0, paint);
// draw object(1) 320x25
// draw object(5) 50x50 each
// draw object(n) 15x15 each, estimate
// draw object(n) 50x50 each
// collision check, draw hit tile on the image sheet

// draw game information using canvas.drawText() timeLine++;

提前致谢!

4

2 回答 2

3

如果问题只是“paint = new Paint();” 行,你为什么不只创建一次 Paint 对象呢?首次创建类并使其成为 Class 变量时。然后只要你想每次都使用这个对象。

于 2011-08-14T20:07:51.947 回答
1

您可以尝试将背景加载为RGB_565而不是ARGB_8888,以防万一。否则,除了切换到 OpenGL 之外,您无能为力

编辑:

Options options = new Options();
options.inDither = false;
options.inJustDecodeBounds = false;
options.inSampleSize = 1;
options.mCancel = false;
options.inPreferredConfig = Config.RGB_565;

bitmap = BitmapFactory.decodeResource(context.getResources(), id, options);

如果这没有帮助,其他原因可能是:

  • 你的绘图代码是错误的
  • 绘制背景时缩放背景
  • 你在模拟器上运行它
于 2011-08-14T15:59:26.020 回答