如何使在画布上绘制的图像对所有屏幕尺寸均有效?我的代码无法正常工作,涂漆的游戏屏幕对于小屏幕来说太大了,对大屏幕来说太小了,我已经尝试了所有方法,但仍然没有任何效果,我希望画布根据屏幕的大小进行缩放
这是我得到的结果,也是所需的结果:https://imgur.com/a/bSnGfov
这是我的游戏画布代码:
public class CanvasView extends View {
Me me;
public int width;
public int height;
public int fx,fy,zx,zy;
int[][]lines;
private Bitmap pme, wall,finish,redlock,redkey,bluelock,bluekey,greenlock,greenkey ,mBitmap,white,c1,c2,c3,c4,c5,c6,c7
,c8,c9,c10,c11,c12;
private Canvas mCanvas;
private Path mPath;
Context context;
private Paint p;
private int mx, my,character;private int dir;
private static final float TOLERANCE = 5;float bb;string bbb; int sz;int fz;
public CanvasView(Context c,int[][] l,Me m,int mxx,int myy,int chara) {
super(c);
lines=l;
mx = mxx;
my = myy;
context = c;
fx=6;fy=6;zx=0;zy=0;
me = m;
character=chara;
mPath = new Path();
p = new Paint();
p.setAntiAlias(true);
p.setColor(Color.BLACK);
p.setStyle(Paint.Style.STROKE);
p.setStrokeJoin(Paint.Join.ROUND);
p.setStrokeWidth(4f);
}
// override onSizeChanged
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// your Canvas will draw onto the defined Bitmap
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
// override onDraw
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = mx;
int height = my;float calc = getResources().getDisplayMetrics().density;
canvas.drawBitmap(pme,calc*( (me.GetCenterX() - 24)+zx),calc*( (me.GetCenterY() - 24)+zy), p);
int px = (me.GetCenterX() - 24) / 48;
int py = (me.GetCenterY() - 24) / 48;
for (int j = 0; j < fx; j++)
{
for (int i = 0; i < fy; i++)
if (i < height)
{
float tileX = ((j * 48) + zx) * calc;
float tileY = ((i * 48) + zy) * calc;
int type = lines[i][j];
switch (type)
{
case 1:
canvas.drawBitmap(wall, tileX,tileY, p);
break;
case 3:
canvas.drawBitmap(finish, tileX,tileY, p);
break;
case 4:
canvas.drawBitmap(bluelock, tileX,tileY, p);
break;
case 5:
canvas.drawBitmap(bluekey, tileX,tileY, p);
break;
case 6:
canvas.drawBitmap(redlock, tileX,tileY, p);
break;
case 7:
canvas.drawBitmap(redkey, tileX,tileY, p);
break;
case 8:
canvas.drawBitmap(greenlock, tileX,tileY, p);
break;
case 9:
canvas.drawBitmap(greenkey, tileX,tileY, p);
break;
}
}
}
}
for (int i = 0; i <= 6;i++ )
{
canvas.drawBitmap(white, 6*48* calc,i*48* calc, p);
}
for (int j = 0; j <= 5; j++)
{
canvas.drawBitmap(white, j*48* calc,6*48* calc, p);
}
}
}
答案 0 :(得分:1)
您可以动态请求Android设备屏幕的尺寸。
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
获取当前显示的句柄-请注意,如果从应用程序上下文调用,则将获得物理屏幕的大小。如果从活动中调用,您将获得应用程序窗口的当前大小。