我有画布我正在绘制位图。我将画布和位图的尺寸设置为变量并打印出它们各自的值。当我尝试绘制位图时,它不显示。
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变量的bottom参数更改为除当前值之外的任何值,则显示位图。例如,如果我改变了
dst = new Rect(.....,canvasWidth*(......));
到
dst = new Rect(.....,canvasWidth));
它会显示。
正如你在logcat输出中看到的那样,
canvasWidth*(memoryManiaHeight/memoryManiaWidth)
被评估为0.为什么会发生这种情况,我该怎么做才能解决它?
答案 0 :(得分:3)
从此处更改您的计算:
canvasWidth*(memoryManiaHeight/memoryManiaWidth)
到此:
(canvasWidth*memoryManiaHeight)/memoryManiaWidth
如果先评估(memoryManiaHeight/memoryManiaWidth)
,那么由于整数除法,它将评估为零。
答案 1 :(得分:2)
memoryManiaHeight
的价值是否有可能小于memoryManiaWidth
?它们都是整数,因此产生零。尝试检查两个变量的值。这应该有效:
(int) ( canvasWidth * ((float)memoryManiaHeight/memoryManiaWidth) );