Android:更改 ImageView 大小无效
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
。 Here's a good webpage that describes the differences.
您可以通过ImageView
的setScaleType方法设置scaleType
。
我正在尝试更改我的 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
。