首页 > 解决方案 > 在 youtube 上构建游戏教程:他们在画布上使用圆形瓷砖,我想使用正方形,我该如何实现?

问题描述

我一直在关注如何在 android studio 上构建蛇的教程:https ://www.youtube.com/watch?v=bPlG7ra83lo

他使用的圆圈组成了一个 28*42 的盒子,如下所示:

圆形网格示例

我希望用正方形替换这些圆圈,但是当我尝试各种方法时,例如:

canvas.drawRect(x*tileSizeX,tileSizeY*x,tileSizeY*y, x, mPaint);

我最终得到这样的输出:

我的尝试

下面是 SnakeView 类中使用的代码:

public class SnakeView extends View {

    private Paint mPaint = new Paint();
    private TileType snakeViewMap[][];
    public SnakeView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public void setSnakeViewMap (TileType[][] map){
        this.snakeViewMap = map;
    }

    @Override
    protected void onDraw (Canvas canvas){
        super.onDraw(canvas);

        if (snakeViewMap != null) {
            float tileSizeX = canvas.getWidth()/snakeViewMap.length;
            float tileSizeY = canvas.getHeight() / snakeViewMap[0].length;

            float circleSize = Math.min(tileSizeX, tileSizeY) /2;

            for (int x=0; x < snakeViewMap.length; x++) {
                for (int y = 0; y <snakeViewMap[x].length; y++) {
                    switch (snakeViewMap[x][y]) {

                    case Nothing:
                        mPaint.setColor(Color.BLACK);
                        break;
                    case Wall:
                        mPaint.setColor(Color.GREEN);
                        break;
                    case SnakeHead:
                        mPaint.setColor(Color.RED);
                        break;
                    case SnakeTail:
                        mPaint.setColor(Color.GREEN);
                        break;
                    case Apple:
                        mPaint.setColor(Color.RED);
                        break;
                    }
                    canvas.drawRect(x*tileSizeX,tileSizeY*x,tileSizeY*y, x, mPaint);
                    //canvas.drawCircle(x * tileSizeX + tileSizeX/2f + circleSize/2, y * tileSizeY + tileSizeY/2f + circleSize/2, circleSize, mPaint);
                }
            }
        }
    }
}

标签: javaandroidandroid-studiocanvas

解决方案


根据https://developer.android.com/reference/android/graphics/Canvas

这是 circle
void drawCircle 的参数(float cx、float cy、float radius、Paint paint)

在哪里

cx  float: The x-coordinate of the center of the cirle to be drawn
cy  float: The y-coordinate of the center of the cirle to be drawn
radius  float: The radius of the cirle to be drawn
paint   Paint: The paint used to draw the circle
This value must never be null.

drawRect(向左浮动,顶部浮动,向右浮动,底部浮动,油漆)

所以你也需要有所改变

代替

 canvas.drawRect(
      x*tileSizeX, //LEFT
      tileSizeY*x, //TOP
      tileSizeY*y, //RIGHT
      x,           //BOTTOM 
      mPaint); 

您需要抵消您的值,使其按以下顺序排列

左上右下

left:  x*tileSizeX
top :  y*tileSizeY
right :  x*tileSizeX +(circleSize*2) //we want the diameter instead of radius
bottom:  y*tileSizeY +(circleSize*2)

推荐阅读