canvas 上未显示位图

Bitmap not showing up on canvas

我有 canvas 正在绘制位图。我将 canvas 和位图的尺寸设置为变量并打印出它们各自的值。当我尝试绘制位图时,它没有显示。

SurfaceView 代码:

protected void onDraw(Canvas canvas) {
    if (canvas != null) {
        canvas.drawColor(Color.WHITE);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        int canvasWidth = canvas.getWidth();
        int canvasHeight = canvas.getHeight();
        int memoryManiaWidth = memoryMania.getWidth();
        int memoryManiaHeight = memoryMania.getHeight();
        Rect src = new Rect(0,0,memoryManiaWidth,memoryManiaHeight);
        Rect dst = new Rect(0,0,canvasWidth,canvasWidth*(memoryManiaHeight/memoryManiaWidth));
        Log.d("MM","CW"+ String.valueOf(canvasWidth));
        Log.d("MM","MMH" + String.valueOf((memoryManiaHeight)));
        Log.d("MM","MMW" + String.valueOf((memoryManiaWidth)));
        Log.d("MM",String.valueOf(canvasWidth*(memoryManiaHeight/memoryManiaWidth)));
        canvas.drawBitmap(memoryMania,src,dst,paint);
    }

}

Logcat 输出:

06-15 21:56:07.395  22939-23030/com.delg.andrew.memorymania D/MM﹕ CW1080
06-15 21:56:07.395  22939-23030/com.delg.andrew.memorymania D/MM﹕ MMH419
06-15 21:56:07.395  22939-23030/com.delg.andrew.memorymania D/MM﹕ MMW951
06-15 21:56:07.395  22939-23030/com.delg.andrew.memorymania D/MM﹕ 0

如果我将 dst Rect 变量的底部参数更改为除其当前值以外的任何值,则会显示位图。例如,如果我更改

dst = new Rect(.....,canvasWidth*(......));

dst = new Rect(.....,canvasWidth));

会显示。

正如您在 logcat 输出中看到的那样,

canvasWidth*(memoryManiaHeight/memoryManiaWidth)

评估为 0。为什么会发生这种情况,我该如何解决?

有没有可能 memoryManiaHeight 的值小于 memoryManiaWidth?它们都是整数,因此产生零。尝试检查两个 variables.And 的值,这应该有效:

(int) ( canvasWidth * ((float)memoryManiaHeight/memoryManiaWidth) );

改变你的计算方式:

canvasWidth*(memoryManiaHeight/memoryManiaWidth)

对此:

(canvasWidth*memoryManiaHeight)/memoryManiaWidth

如果您先计算 (memoryManiaHeight/memoryManiaWidth),那么由于整数除法,它将计算为零。