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

10

如何在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>

Java:

ImageView iv = (ImageView) findViewById(R.id.fruit);
LayoutParams frame = iv.getLayoutParams();
frame.width = 100;
iv.setLayoutParams(frame);

编辑: 我希望图片能够在我设置的边界内裁剪,并且表格单元格保留原始宽度。以下是代码示例,感谢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);
2个回答

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

2
您想要对图片进行缩放吗?或者裁剪它?
要进行缩放,可以尝试使用 ImageView.setImageMatrix 和 Matrix.preScale
如果您不想自己算矩阵,可以尝试使用矩形框(bounding boxes)来实现。使用 ImageView.getDrawingRect 获取原始的矩形框,然后定义所需的矩形框,再使用 Matrix.setRectToRect 来创建您的图像矩阵。
否则,您是否尝试过使用 ImageView.setMaxWidth

setMaxWidth没有起作用。我尝试了你的建议,但Matrix.setRectToRect需要一个Bitmap.Config来缩放图像。 - caseadilla

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接