将图像拟合到ButtonImage



我正在尝试将ImageButtons适应不同屏幕大小的背景图像大小。图像存储在可绘制文件夹(可绘制hdpi、可绘制xhdpi等)中。

我一直在四处寻找,但答案非常过时,或者它们只是缩放图像。

这是我使用过的布局,但我必须对TableRows进行编程,所以这并不是全部。

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/MyTableLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:screenOrientation="landscape"
    tools:ignore="MergeRootFrame">
    <TableRow
        android:id="@+id/MyTableRow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"></TableRow>
</TableLayout>

我用ImageButtons(有点像矩阵)创建了一些行

(您可以忽略参数X和Y,因为它们不会影响图像)。

/* OnCreate()...
    myTableRow = ((TableRow) findViewById(R.id.MyTableRow));
    mainTable = new TableLayout(context);
    myTableRow.addView(mainTable, screenHeight, screenWidth / 2);
    for (int y = 0; y < MAX_NUMBER; y++)
        mainTable.addView(createRow(y));
*/
private TableRow createRow(int y) {
    TableRow row = new TableRow(context);
    row.setHorizontalGravity(Gravity.CENTER);
    for (int x = 0; x < MAX_NUMBER; x++)
        row.addView(createImageButton(x, y));
    return row;
}

图像"myImage"具有不同的大小,具体取决于屏幕的大小。按钮的大小应该与图像的大小完全相同。但我很难实现它…

private View createImageButton(int x, int y) {
    ImageButton button = new ImageButton(context);      
    // Adjust button size (?)
    button.setLayoutParams(new TableRow.LayoutParams(myImage.getMinimumWidth(),
             myImage.getMinimumHeight(), 1f));
        //It doesn't work at all
    button.setBackground(myImage);
    ...
    return button;
}

你有什么想法吗??感谢

尝试以下操作:

使用android:scaleType="fitCenter"让Android缩放图像,使用android:adjustViewBounds="true"让它们根据缩放调整边界。

<ImageButton
        android:id="@+id/button_topleft"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="0dp"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:padding="20dp"
        android:scaleType="fitCenter" />

试试这个

button.setScaleType(ScaleType.FIT_XY)

private View createImageButton(int x, int y) {
    ImageButton button = new ImageButton(context);      
    // Adjust button size (?)
    button.setLayoutParams(new TableRow.LayoutParams(myImage.getMinimumWidth(),
            myImage.getMinimumHeight(), 1f));
        //It doesn't work at all
    button.setBackground(myImage);
    button.setScaleType(ScaleType.FIT_XY)
    ...
    return button;
}

最新更新