我正在为Android制作游戏并使用SurfaceView。
我想知道智能手机屏幕信息(高度,宽度等)
我使用了这段代码,但是..显示宽度和高度
的值不正确红色总是打印“0”
我想念的是什么?
public class MainActivity extends Activity {
private int width;
private int height;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
width = metrics.widthPixels;
height = metrics.heightPixels;
setContentView(new GameView(this));
}
public class Painter extends Thread
public void run(){
Canvas canvas = null;
long start, end;
int sleep;
while(true) {
if (runnable) {
start = System.currentTimeMillis();
try {
canvas = holder.lockCanvas(null);
paint.setColor(Color.RED);
paint.setTextSize(200);
synchronized (holder) {
canvas.drawText(Integer.toString(main.getHeight()), 600, 800, paint);
canvas.drawText(Integer.toString(main.getWidth()), 300, 400, paint);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
holder.unlockCanvasAndPost(canvas);
}
end = System.currentTimeMillis();
sleep = 1000 / FPS - (int) (end - start);
try {
Thread.sleep(sleep > 0 ? sleep : 0);
} // Try
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:4)
您可以使用此代码获取它:
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
适用于所有API版本,因此无需API检查。 如果您在视图中,则可能需要获取上下文:
((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
答案 1 :(得分:1)
您可以使用以下代码获取显示高度和宽度。
OpenGL version string: 3.0 Mesa 10.3.2
答案 2 :(得分:1)
/*
* A structure describing general information about a display, such as its size, density, and font scaling.
* */
DisplayMetrics metrics = getResources().getDisplayMetrics();
int DeviceTotalWidth = metrics.widthPixels;
int DeviceTotalHeight = metrics.heightPixels;
答案 3 :(得分:0)
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width=dm.widthPixels;
int height=dm.heightPixels;
int dens=dm.densityDpi;
double wi=(double)width/(double)dens;
double hi=(double)height/(double)dens;
double x = Math.pow(wi,2);
double y = Math.pow(hi,2);
double screenInches = Math.sqrt(x+y);