Skip to content Skip to sidebar Skip to footer

Android Placing Bitmap In Middle

I am designing a drawing app where user can import image from gallery and then scale up or down to fit the screen width or height. so that user can draw onto the imported picture,

Solution 1:

// You can try this :         int width = containerBitmap.getWidth();
            int height = containerBitmap.getHeight();
            float centerX = (width  - centeredBitmap.getWidth()) * 0.5f;
            float centerY = (height- centeredBitmap.getHeight()) * 0.5f;
            mCanvas.drawBitmap(centeredBitmap, centerX, centerY, paint);

You can use it to draw a bitmap at the center of another bitmap.

Solution 2:

In your onDraw() you specify (0,0) as the bitmap (x,y) which will draw it at the top left corner of your DrawView so your x_adjustment, y_adjustment effect is lost once onDraw is called.

You should do your bitmap location adjustment code inside onDraw not inside onClick

@OverrideprotectedvoidonDraw(Canvas canvas)// called each time this View is drawn 
{
  canvas.drawBitmap(bitmap, x_adjustment, y_adjustment, null);       
} 

Solution 3:

The LayoutParameters of your imageview or the imageview's parent view need to specify centering within the screen

also, post your XML layout if there is one, as well as where you make the bitmap part of an imageview in your code

Solution 4:

As iTech has noted, to get your Bitmap drawn in the center of the DrawView, you need to draw it in the correct location inside your onDraw method.

Create two additional fields:

int x_adjust, y_adjust;

In your onClick (when loading the bitmap), calculate the correct center, and set x_adjust and y_adjust to the relevant values. Then make sure you use these values in the onDraw method (rather than 0,0).

@OverrideprotectedvoidonDraw(Canvas canvas)
{
    canvas.drawBitmap(bitmap, x_adjust, y_adjust, null);       
}

Note: Make sure to recalculate x_adjust and y_adjust in the onSizeChanged method also. Otherwise the bitmap will no longer be centered after you rotate the device.

Post a Comment for "Android Placing Bitmap In Middle"