How to create white border around bitmap?

后端 未结 8 1719
萌比男神i
萌比男神i 2021-02-12 19:24

For example I want a white border of 10pixel around all 4 side of the bitmap. I am not using it for imageview I am currently using this code to crop image. May I know how I coul

相关标签:
8条回答
  • 2021-02-12 19:45

    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.

    0 讨论(0)
  • 2021-02-12 19:45

    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.

    0 讨论(0)
提交回复
热议问题