缩放到高分辨率时,绘制位图很慢

时间:2012-02-02 10:41:56

标签: android performance bitmap drawing scale

我有一个非常简单的任务,即在自定义视图中绘制背景图像。我创建一个位图并缩放它以适应视图的宽度和高度。这使app变得更慢,就像快一半(我每10毫秒打印一次时间值来测量性能的速度)。 这是代码:

public class GView extends View {

int w, h;
Bitmap bg;
int time = 0;

boolean created = false;
public GView(Context context) {
    super(context);
    bg = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
    new Timer();
}

@Override
public void onDraw(Canvas c) {
    Paint p = new Paint();
    if(!created) {
        w=getWidth();
        h=getHeight();
        p.setColor(Color.RED);
        p.setTextSize(40);
        bg = Bitmap.createScaledBitmap(bg, w, h, false);
        created = true;
    }
    if(created) {
        time++;
        c.drawBitmap(bg, 0,0,null);
        c.drawText(time+"", (int)(w/4),  (int)(h/4), p);
    }

}

class Timer extends Handler {
    private Timer() {
        handleMessage(obtainMessage(0));
    }

    @Override
    public void handleMessage(Message m) {
        invalidate();
        sendMessageDelayed(obtainMessage(0), 10);
    }
}

}

仅供参考,原始图像为300x225。我将图像缩放到的平板电脑的屏幕分辨率为1280x800。 问题是如果我将背景图像缩放到类似(int)(。8 * w),(int)(。8 * h)或者更小或者根本不缩放图像,那么它会按预期快速运行。 / p>

我尝试使用ImageView并使用setImageResource(R.drawable.my_image),但它虽然很慢。 我认为绘制适合背景的图像应该对任何编程语言都非常简单,但是即使经过大量搜索,我已经有很长时间没有这个问题了。我希望有人能给我一个正确的答案。我真的很感激。

1 个答案:

答案 0 :(得分:1)

createScaledBitmap()不应该在onDraw()例程中完成。它非常慢,因为它使用像素平均例程来“平滑”拉伸的位图。在gui线程之外创建拉伸位图,然后在onDraw()方法中绘制它(canvas.drawBitmap)。如果设置为false,则filter参数可用于创建“最近邻居”缩放。这将看起来“块状”,但处理速度要快得多。

public static Bitmap createScaledBitmap
  (Bitmap src, int dstWidth, int dstHeight, boolean filter)