Android:如何以编程方式在TableRow中设置ImageView的宽度

cas*_*lla 10 android android-layout

如何以编程方式在TableRow中设置ImageView的宽度?我不希望单元格宽度发生变化,只需更改单元格内图像的宽度.

布局:(省略号是为了减少代码)

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal">
<TableRow android:gravity="center_vertical">
<Button>...</Button>
<ImageView
    android:id="@+id/fruit"
    android:layout_width="120dp"
    android:layout_height="44dp"
    android:src="@drawable/apple"
    android:scaleType="matrix"
></ImageView>
<Button>...</Button>
</TableRow>
<TableRow>...</TableRow>
</TableLayout>
Run Code Online (Sandbox Code Playgroud)

Java的:

ImageView iv = (ImageView) findViewById(R.id.fruit);
LayoutParams frame = iv.getLayoutParams();
frame.width = 100;
iv.setLayoutParams(frame);
Run Code Online (Sandbox Code Playgroud)

编辑:我希望在我设置的边界内裁剪图像,并让表格单元格为原始宽度.下面是代码示例,感谢parag的建议:

Bitmap bmp = BitmapFactory.decodeResource(getResources() , R.drawable.apple); 
int width = 50;
int height = 44; 
Bitmap resizedbitmap = Bitmap.createBitmap(bmp, iv.getScrollX(), iv.getScrollY(), width, height);
iv.setImageBitmap(resizedbitmap);
Run Code Online (Sandbox Code Playgroud)

Par*_*han 31

另一种调整位图大小的方法

    ImageView img=(ImageView)findViewById(R.id.ImageView01);
    Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.sc01);
    int width=200;
    int height=200;
    Bitmap resizedbitmap=Bitmap.createScaledBitmap(bmp, width, height, true);
    img.setImageBitmap(resizedbitmap);
Run Code Online (Sandbox Code Playgroud)