在ImageView中使Android位图居中

3

我有一个ImageView,用于显示Bitmap。当我将Bitmap设置到ImageView中时,它并不居中显示。我也尝试使用scaleType属性设置为center、centerCrop和centerInside。

这是我的布局文件中的ImageView:

    android:id="@+id/xyz"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="15dp"
    android:layout_marginTop="3dp"
    android:layout_weight="1.03"
    android:background="#FFFFFFFF" 
    android:adjustViewBounds="true"
    android:scaleType="fitXY"

编辑:这是调整位图大小的代码:

private void scaleImage() {
    Bitmap bitmap = getHostPage().getBackgroundDrawing();

    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    int bounding = dpToPx(250);
    float xScale = ((float) bounding) / width;
    float yScale = ((float) bounding) / height;

    Matrix matrix = new Matrix();
    matrix.postScale(xScale, yScale);

    Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    width = scaledBitmap.getWidth(); 
    height = scaledBitmap.getHeight(); 
    BitmapDrawable result = new BitmapDrawable(scaledBitmap);

    getHostPage().setBackgroundDrawing(result.getBitmap());
    
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) drawView.getLayoutParams(); 
    params.width = width;
    params.height = height;
    drawView.setLayoutParams(params);

}

private int dpToPx(int dp) {
    float density = hostPage.getHostActivity().getApplicationContext().getResources().getDisplayMetrics().density;
    return Math.round((float)dp * density);
}

bitmap


android:gravity="center_horizontal" 或 android:layout_gravity="center_horizontal" - Illegal Argument
你也可以使用FrameLayout。 - Elementary
3个回答

1

use this :

android:gravity="center|center_vertical"
android:layout_gravity="center|center_vertical"

<RelativeLayout android:id="@+id/imageLinearLayout" android:layout_width="match_parent" android:layout_height="match_parent"> <com.numberatank.Utils.TouchImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center|center_horizontal" android:layout_gravity="center|center_horizontal" android:layout_centerInParent="true" /></RelativeLayout> - Jitendra Bhadja
这个ImageView无法正常工作。我已经尝试在RelativeLayout中使用它,但是设置位图的左侧时没有居中显示。 - Jitendra Bhadja

1
在您的图像视图 XML 代码中添加以下内容:

android:layout_centerHorizontal="true"

我认为这可能会对你有所帮助。

谢谢。


0
    android:id="@+id/xyz"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="15dp"
    android:layout_marginTop="3dp"
    android:layout_weight="1.03"
    android:background="#FFFFFFFF" 
    android:gravity="center"
    android:adjustViewBounds="true"
    android:scaleType="fitXY"

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