繁体   English   中英

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

[英]Android: how to programmatically set width of ImageView inside TableRow

如何以编程方式在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);

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

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

你想缩放图像吗? 还是剪呢?

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

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

否则,你试过ImageView吗? setMaxWidth

暂无
暂无

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

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