Android How to - Center a Bitmap








Question

We would like to know how to center a Bitmap.

Answer

The following code shows how to center a Bitmap.

It creates a new Bitmap from the existing one and calculates new width and height.

/*  ww w .j  a  v  a2  s.  c o  m*/
import android.graphics.Bitmap;

public class Main {

    public static Bitmap centerCrop(Bitmap srcBmp) {
        Bitmap dstBmp = null;
        if (srcBmp.getWidth() >= srcBmp.getHeight()) {

            dstBmp = Bitmap.createBitmap(
                    srcBmp,
                    srcBmp.getWidth() / 2 - srcBmp.getHeight() / 2,
                    0,
                    srcBmp.getHeight(),
                    srcBmp.getHeight()
                    );

        } else {

            dstBmp = Bitmap.createBitmap(
                    srcBmp,
                    0,
                    srcBmp.getHeight() / 2 - srcBmp.getWidth() / 2,
                    srcBmp.getWidth(),
                    srcBmp.getWidth()
                    );
        }
        return dstBmp;
    }
}