我正在画布上绘制图像,然后又将其全屏显示在导航栏和状态栏的后面。
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.background_try9);
bgTrans = Bitmap.createScaledBitmap(b, canvas.getWidth(), canvas.getHeight(), false);
canvas.drawBitmap(bgTrans, 0, 0, paint);
}
现在我想将其移至onDraw
方法之外。
我知道我可以这样使用DisplayMetrics
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
int width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;
但是我读到有时它可以报告错误/空值。另外,在签出后,似乎heightPixels不计算导航栏的高度。输入onDraw
之前可以获取画布尺寸吗?
答案 0 :(得分:0)
获取导航栏的高度,并从屏幕的高度上减去它!
尝试以下代码:
Resources resources = context.getResources();
int navBarId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
int statusBarId = resources.getIdentifier("status_bar_height", "dimen", "android");
int navBarHeight = 0;
int statusBarHeight = 0;
if (resourceId > 0) {
navBarHeight = resources.getDimensionPixelSize(navBarId);
statusBarHeight = resources.getDimensionPixelSize(statusBarId);
}
DisplayMetrics displayMetrics = resources.getDisplayMetrics();
int width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;
height = height + navBarHeight + statusBarHeight;
此代码未经测试,但我认为它有效!我记得遇到过这个问题,所以我使用了这种方法。
获取屏幕尺寸的另一种方法是:
// Inside an Activity or if you have a reference of activity
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;