How to create a square bitmap from a rectangular bitmap in Android

后端 未结 2 1357
不思量自难忘°
不思量自难忘° 2021-02-09 00:21

Basically, I have a rectangular bitmap and want to create a new Bitmap with squared dimensions which will contain the rectangular bitmap inside of it.

So, for example, i

相关标签:
2条回答
  • 2021-02-09 01:07

    Try this:

        private static Bitmap createSquaredBitmap(Bitmap srcBmp) {
            int dim = Math.max(srcBmp.getWidth(), srcBmp.getHeight());
            Bitmap dstBmp = Bitmap.createBitmap(dim, dim, Config.ARGB_8888);
    
            Canvas canvas = new Canvas(dstBmp);
            canvas.drawColor(Color.WHITE);
            canvas.drawBitmap(srcBmp, (dim - srcBmp.getWidth()) / 2, (dim - srcBmp.getHeight()) / 2, null);
    
            return dstBmp;
        }
    
    0 讨论(0)
  • 2021-02-09 01:15

    Whoops, just realized what the problem is. I was drawing the wrong Bitmap to the Canvas. If it helps anyone in the future, remember that the Canvas is already attached and will paint to the bitmap you specify in its constructor. So basically:

    This:

    c.drawBitmap(resultBitmap, sourceRect, destinationRect, null);
    

    Should actually be:

    c.drawBitmap(sourceBitmap, sourceRect, destinationRect, null);
    
    0 讨论(0)
提交回复
热议问题