我知道如何使用其 layoutParams 的重力属性使 imageView 居中。但是,我试图让它集中在它的边距上。如果图像的宽度为 w,而显示窗口的宽度为 W,我的猜测是 leftMargin = rightMargin = W/2 - w/2。同样,topMargin = bottomMargin = H/2 - h/2。结果是 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);
如果状态栏和标题栏被隐藏,则图像居中,所以我猜显示窗口大小有问题。