首页 > 解决方案 > Canvas 的 drawBitmap 方法导致缩放后性能不佳

问题描述

我正在尝试为 Bitmap 对象创建一个简单的平移运动。我通过创建一个画布并将一个帧缓冲区传递给它来做到这一点,该缓冲区之前已初始化为 1080/1920 的分辨率。然后我继续通过调用画布的方法 drawBitmap() 来绘制位图,如下所示:

this.canvas = new Canvas(frameBuffer);

...

canvas.drawBitmap(bitmap, null, destinationRect, paint);

在设置为主要活动的内容视图的另一个线程中,我正在缩放帧缓冲区以适应实际的屏幕尺寸,然后使用这些行绘制它的所有内容:

Canvas canvas = holder.lockCanvas();
canvas.getClipBounds(dstRect);

...

canvas.drawBitmap(framebuffer, null, dstRect, paint);
holder.unlockCanvasAndPost(canvas);

这导致性能非常差,无论是使用增量时间手动测量还是使用 Android Studio 工具进行监控。即使在视觉上,您也可以在位图之后看到带有非常低的 fps 的尾随。

我似乎找不到造成这种情况的原因,但我怀疑 drawBitmap 隐式执行的缩放过程正在做一些沉重的事情。我尝试更改过滤器设置但没有成功。我也怀疑我是否应该为这个简单的需求而选择 openGL。

我应该使用不同大小的位图并在运行时决定最接近我需要的大小,还是有更直接的解决方案来解决这个问题?

编辑:这是我使用 matrix.postScale() 方法每秒获得更多帧的方法:

        int width = framebuffer.getWidth();
        int height = framebuffer.getHeight();
        float scaleWidth = ((float) game.size.x) / width;
        float scaleHeight = ((float) game.size.y) / height;
        // create a matrix for the manipulation
        Matrix matrix = new Matrix();
        // resize the bit map
        matrix.postScale(scaleWidth, scaleHeight);
        // recreate the new Bitmap
        Bitmap resizedBitmap = Bitmap.createBitmap(framebuffer, 0, 0, width, height, matrix, true);

        canvas.drawColor(Color.parseColor("#013501"));
        canvas.drawBitmap(resizedBitmap, null, dstRect, paint);
        holder.unlockCanvasAndPost(canvas);

标签: androidcanvasbitmapdrawscaling

解决方案


推荐阅读