How to create white border around bitmap?

I wrote a function for this:

private Bitmap addWhiteBorder(Bitmap bmp, int borderSize) {
    Bitmap bmpWithBorder = Bitmap.createBitmap(bmp.getWidth() + borderSize * 2, bmp.getHeight() + borderSize * 2, bmp.getConfig());
    Canvas canvas = new Canvas(bmpWithBorder);
    canvas.drawColor(Color.WHITE);
    canvas.drawBitmap(bmp, borderSize, borderSize, null);
    return bmpWithBorder;
}

Basically it creates a new Bitmap adding 2 * bordersize to each dimension and then paints the original Bitmap over it, offsetting it with bordersize.


the accepted answer is nice but in the cases that bitmap contains a transparent background, it fills all over the background of source bitmap with white pixels. so it doesn't work fine for all cases.

a better way to achieve this goal is using Canvas#drawLine method like the following code:

    Bitmap drawBorder(Bitmap source) {
    int width = source.getWidth();
    int height = source.getHeight();
    Bitmap bitmap = Bitmap.createBitmap(width, height, source.getConfig());
    Canvas canvas = new Canvas(bitmap);
    Paint paint = new Paint();
    paint.setStrokeWidth(50);
    paint.setColor(Color.WHITE);

    canvas.drawLine(0, 0, width, 0, paint);
    canvas.drawLine(width, 0, width, height, paint);
    canvas.drawLine(width, height, 0, height, paint);
    canvas.drawLine(0, height, 0, 0, paint);
    canvas.drawBitmap(source, 0, 0, null);

    return bitmap;
        }

in this way we first create a second bitmap using source bitmap width, height and config and use drawline() mathod four times to draw four lines using coordinates of end points of each line around the second bitmap and then draw the source bitmap on the second bitmap that must be returned.


As for a way of doing this. You make your bitmap bigger than the one your adding to it and then fill the canvas with the background you want. If you need to add other effects you can look into the canvas options for clipping the rect and adding rounded corners and such.

RectF targetRect = new RectF(left+10, top+10, left + scaledWidth, top + scaledHeight);
Bitmap dest = Bitmap.createBitmap(newWidth+20, newHeight+20, source.getConfig());
Canvas canvas = new Canvas(dest);
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(source, null, targetRect, null);

You can draw 4 rectangles after painting your bitmap's stuff.

point 0,0,3,sizey
point 0,0,sizex,3
point 0,sizey-3,sizex,sizey
point sizex-3,0,sizex,sizey

Tags:

Android

Bitmap