【问题标题】:Android: onDraw is too slowAndroid:onDraw 太慢了
【发布时间】:2011-10-26 20:00:24
【问题描述】:

我正在使用 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

//使用canvas.drawText()绘制游戏信息 时间线++;

提前致谢!

【问题讨论】:

    标签: android canvas surfaceview ondraw


    【解决方案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);
    

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

    • 你的绘图代码错误
    • 绘制背景时缩放背景
    • 你在模拟器上运行它

    【讨论】:

    • 恐怕该行返回错误。我已经检查了 API,BitmapFactory.decodeResource 的唯一 3 个参数必须是(上下文上下文、int id、选项选项)。
    • 不幸的是,感觉只有毫秒的差异。
    • 我已经放置了onDraw方法的基本部分。
    • 您是在 lockCanvas() 和 unlockCanvasAndPost() 之间的后台线程中执行此操作的吗?在那种情况下,我不知道。
    • 是的。不过是不是因为图片文件大小的原因,目前壁纸的文件大小已经在500KB左右了?
    【解决方案2】:

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

    【讨论】:

    • 实际上,该行在onCreate()上执行了一次。
    猜你喜欢
    • 2013-03-10
    • 2014-06-07
    • 2016-05-31
    • 2011-07-07
    • 2015-08-23
    • 2012-07-05
    • 2016-01-08
    • 2014-03-12
    • 2021-03-26
    相关资源
    最近更新 更多