我正在尝试更改我的 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
。 Here's a good webpage that describes the differences.
您可以通过ImageView
的setScaleType 设置scaleType
方法。
关于java - Android:更改 ImageView 大小不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37093506/