csnewb
csnewb

Reputation: 1270

Android center Bitmap in ImageView

I have got an ImageView, which shows a Bitmap. When I set my Bitmap to the ImageView, it is not centered. I also tried to set scaleType to center, centerCrop, centerInside.

That's my ImageView in Layout:

    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"

EDIT: that is the code which resizes the bitmap:

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

Upvotes: 3

Views: 3749

Answers (3)

Meysam
Meysam

Reputation: 694

use this :

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

Upvotes: 1

msevgi
msevgi

Reputation: 4904

    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"

Upvotes: 0

Carshtokky
Carshtokky

Reputation: 86

Add this in your image view xml code :

android:layout_centerHorizontal="true"

I think it may help you.

Thanks.

Upvotes: 1

Related Questions