gpt4 book ai didi

java - Android - 在 Canvas 中绘制位图

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:41:15 24 4
gpt4 key购买 nike

我目前有一个迷宫游戏,它绘制了一个 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);

然后我还需要为 Canvas 中的所有其他方 block 实现背景图像。此背景将在其顶部绘制简单的 1px 黑线,当前代码在灰色背景中绘制。

background = new Paint();
background.setColor(bgColor);
canvas.drawRect(0, 0, width, height, background);

如果可能的话,请您指点一下。如果是这样,我能做到这一点的最佳方法是什么,同时尽量减少内存使用并拥有 1 张图像,该图像将扩展和收缩以填充相关的正方形空间(这在所有不同的屏幕尺寸上有所不同,因为它会分割整体屏幕宽度均匀)。

最佳答案

使用Canvas方法public void drawBitmap (Bitmap bitmap, Rect src, RectF dst, Paint paint)。将 dst 设置为您希望将整个图像缩放到的矩形的大小。

编辑:

下面是在 Canvas 上以正方形绘制位图的可能实现。假设位图位于二维数组中(例如,Bitmap bitmapArray[][];)并且 Canvas 是方形的,因此方形位图的纵横比没有失真。

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);
}
}

关于java - Android - 在 Canvas 中绘制位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13361231/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com