我目前有一个5 x 5平方的迷宫游戏(占用屏幕宽度并均匀分割)。然后,对于使用x和y坐标的每个框,我使用drawRect来绘制彩色背景。
我遇到的问题是我现在需要在同一位置绘制图像,因此替换当前的普通背景颜色填充。
这是我目前用于drawRect的代码(一些例子):
// these are all the variation of drawRect that I use
canvas.drawRect(x, y, (x + totalCellWidth), (y + totalCellHeight), green);
canvas.drawRect(x + 1, y, (x + totalCellWidth), (y + totalCellHeight), green);
canvas.drawRect(x, y + 1, (x + totalCellWidth), (y + totalCellHeight), green);
然后我还需要为画布中的所有其他方块实现背景图像。此背景将在其顶部绘制简单的1px黑色线条,当前代码以灰色背景绘制。
background = new Paint();
background.setColor(bgColor);
canvas.drawRect(0, 0, width, height, background);
如果可能的话,请你指点一下。如果是这样,那么我可以做的最好的方法是什么,同时尽量减少内存使用量并使1个图像扩展和缩小以填充相关的方形空间(这会因所有不同的屏幕尺寸而变化,因为它会分裂整体屏幕宽度均匀)。
答案 0 :(得分:7)
使用Canvas
方法public void drawBitmap (Bitmap bitmap, Rect src, RectF dst, Paint paint)
。将dst
设置为您想要缩放整个图像的矩形的大小。
修改强>
这是在画布上绘制正方形中的位图的可能实现。假设位图是二维数组(例如,Bitmap bitmapArray[][];
),并且画布是方形的,因此方形位图宽高比不会失真。
private static final int NUMBER_OF_VERTICAL_SQUARES = 5;
private static final int NUMBER_OF_HORIZONTAL_SQUARES = 5;
...
int canvasWidth = canvas.getWidth();
int canvasHeight = canvas.getHeight();
int squareWidth = canvasWidth / NUMBER_OF_HORIZONTAL_SQUARES;
int squareHeight = canvasHeight / NUMBER_OF_VERTICAL_SQUARES;
Rect destinationRect = new Rect();
int xOffset;
int yOffset;
// Set the destination rectangle size
destinationRect.set(0, 0, squareWidth, squareHeight);
for (int horizontalPosition = 0; horizontalPosition < NUMBER_OF_HORIZONTAL_SQUARES; horizontalPosition++){
xOffset = horizontalPosition * squareWidth;
for (int verticalPosition = 0; verticalPosition < NUMBER_OF_VERTICAL_SQUARES; verticalPosition++){
yOffset = verticalPosition * squareHeight;
// Set the destination rectangle offset for the canvas origin
destinationRect.offsetTo(xOffset, yOffset);
// Draw the bitmap into the destination rectangle on the canvas
canvas.drawBitmap(bitmapArray[horizontalPosition][verticalPosition], null, destinationRect, null);
}
}
答案 1 :(得分:2)
请尝试以下代码:
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawBitmap(bitmap, x, y, paint);
==================
您也可以引用此answer。