[英]Android: Changing ImageView size is not working
我正在尝试更改我的 ImageView 大小,但我似乎无法同时更改 - 宽度和高度。 如果我只更改其中之一,则一切正常,但是当我尝试更改两者时,仅更改了宽度。
我有 dp 的大小:宽度 22 和高度 38,我将它们转换为 px。 还有另一种方法吗? 我尝试了很多其他方法,但它们似乎也不起作用。
有人可以告诉我,我应该怎么做?
这是我的代码:
public GridLayout gridLayout;
public GridLayout.Spec row = GridLayout.spec(0);
public GridLayout.Spec col = GridLayout.spec(3);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridLayout = (GridLayout) findViewById(R.id.gameGrid);
createBlock();
}
public void createBlock() {
ImageView block = new ImageView(this);
block.setImageResource(R.drawable.red);
if (gridLayout != null) {
gridLayout.addView(block, new GridLayout.LayoutParams(row, col));
int width_in_dp = 22, height_in_dp = 38;
final float scale = getResources().getDisplayMetrics().density;
int width_in_px = (int) (width_in_dp * scale + 0.5f);
int height_in_px = (int) (height_in_dp * scale + 0.5f);
ViewGroup.LayoutParams layoutParams = block.getLayoutParams();
layoutParams.width = width_in_px;
layoutParams.height = height_in_px;
block.setLayoutParams(layoutParams);
}
}
您是否尝试过使用block
的scaleType
? 默认为fitCenter
但我通常选择centerCrop
或fitXY
。 这是一个很好的网页,描述了这些差异。
您可以通过ImageView
的setScaleType方法设置scaleType
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.