0
我知道如何使用其layoutParams的重力属性将imageView居中。不过,我试图让它集中在边缘游戏中。如果图像的宽度为w,显示窗口的宽度为W,我的猜测是leftMargin = rightMargin = W/2 - w/2。同样,topMargin = bottomMargin = H/2 - h/2。结果是imageView水平居中,但没有垂直居中。下面的代码:为什么imageView不能居中?
// new layout, blue background
FrameLayout root = new FrameLayout(this);
root.setBackgroundColor(getResources().getColor(R.color.blue));
// window dimensions
Point window = new Point();
getWindowManager().getDefaultDisplay().getSize(window);
// imageView with bitmap
ImageView img = new ImageView(this);
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.square);
img.setImageBitmap(bm);
// imageView layout params
int w = bm.getWidth();
int h = bm.getHeight();
FrameLayout.LayoutParams p = new FrameLayout.LayoutParams(w, h);
p.setMargins(window.x/2 - w/2, window.y/2 - h/2, window.x/2 - w/2, window.y/2 - h/2);
img.setLayoutParams(p);
// add image to root layout
root.addView(img);
// set layout as main layout
setContentView(root);
如果状态栏和标题栏被隐藏,则图像被集中,所以我想有什么东西与显示窗口的大小。
是的。就是这样。我不明白为什么API不提供另一种方式来捕捉布局高度 – marc