java - 在 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);
}
}
}
}
}
解决方案
根据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)
推荐阅读
- sql - 无法在 sql shell 上执行在 pgAdmin 中创建的函数:“函数...不存在”
- stata - 在 stata 的 do-file 的序言中始终包含哪些命令?
- python - django celery 显示错误 -- Process "ForkPoolWorker-1" pid:41 exited with "exitcode 70"
- javascript - 单击选择选项javascript后如何显示警报?
- android - 在 Android Recorder 程序中获取 IOException
- javascript - 选择选项后如何显示选择的选项
- react-native - React native react-native-camera 和 @leesiongchan/react-native-esc-pos 都出现错误
- ios - 带有fastlane和flutter的Github工作流缓存路径
- c - 我需要反转用户在 C 中输入的 5 位数字。代码没有语法错误(没有错误曲线),但代码仍然无法运行
- html - 按下浏览器上的后退箭头按钮后返回页面时,HTML CSS 和 JAVASCRIPT 无法正常工作