2011-01-27 102 views
9

如何以编程方式设置TableRow中ImageView的宽度?我不希望单元格宽度改变,只有单元格内部图像的宽度。Android:如何以编程方式设置ImageView的宽度TableRow

布局:(省略号是有减少的代码)

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

回答

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

正是我所需要的 – keybee 2013-08-28 10:10:05

2

要缩放图像吗?还是裁剪?

要缩放,请尝试ImageView。 setImageMatrix和Matrix。 preScale

如果你不想找出矩阵,你可以尝试Rects(边界框)。用ImageView获取原始矩形。 getDrawingRect然后定义你想要的任何Rect并使用Matrix。 setRectToRect来创建您的图像矩阵。

否则,你试过ImageView。 setMaxWidth

+0

setMaxWidth没有工作。我尝试了你的建议,但Matrix.setRectToRect需要一个缩放图像的Bitmap.Config。 – caseadilla 2011-01-27 19:22:16

相关问题