Android:更改ImageView大小无效

时间:2016-05-07 20:43:43

标签: java android imageview size

我正在尝试更改我的ImageView大小,但我似乎无法改变它们 - 宽度和高度。如果我只更改其中一个,那么一切正常,但当我尝试更改两者时,只更改宽度。

我的大小在dp:width 22和height 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);

    }
}

1 个答案:

答案 0 :(得分:1)

您是否尝试过使用block scaleType?默认值为fitCenter,但我通常会选择centerCropfitXYHere's a good webpage that describes the differences.

您可以设置scaleTypeImageView' setScaleType方法。