簡體   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