简体   繁体   English

Android:更改 ImageView 大小不起作用

[英]Android: Changing ImageView size is not working

I am trying to change my ImageView size, but I can't seem to change both - width and height.我正在尝试更改我的 ImageView 大小,但我似乎无法同时更改 - 宽度和高度。 If I just change one of them, then all works correctly, but when I try to change both, only width is changed.如果我只更改其中之一,则一切正常,但是当我尝试更改两者时,仅更改了宽度。

I have the size in dp: width 22 and height 38, and I convert them to px.我有 dp 的大小:宽度 22 和高度 38,我将它们转换为 px。 Is there another way to do so?还有另一种方法吗? I have tried many other ways, but they don't seem to work either.我尝试了很多其他方法,但它们似乎也不起作用。

Could someone tell me, what I should do differently?有人可以告诉我,我应该怎么做?

Here is my code:这是我的代码:

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);

    }
}

Have you tried playing with the block 's scaleType ?您是否尝试过使用blockscaleType The default is fitCenter but I usually choose centerCrop or fitXY .默认为fitCenter但我通常选择centerCropfitXY Here's a good webpage that describes the differences. 这是一个很好的网页,描述了这些差异。

You can set the scaleType through ImageView 's setScaleType method.您可以通过ImageViewsetScaleType方法设置scaleType

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM