Add Padding to Android.Graphics.Bitmap

Nathan Sokalski 4,116 Reputation points
2022-08-28T22:43:28.36+00:00

I have an Android.Graphics.Bitmap that I want to resize by adding padding to the right and/or bottom. I do not want to scale the Bitmap, so I cannot use Bitmap.CreateScaledBitmap. Is there any simple way to do this?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,292 questions
0 comments No comments
{count} votes

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 68,261 Reputation points Microsoft Vendor
    2022-08-29T05:53:41.66+00:00

    Hello,

    If you want to add right and bottom padding to the Bitmap, you need to create a new Bitmap, add the bigger width and height (it depends on your padding's size), then use Canvas to draw it in the top-left corner.

    Here is demo code.

       private Bitmap AddRightAndBottomPaddingForBitmap(Bitmap Orignalbitmap, int paddingSize)  
               {  
                   //I add padding for right and bottom at the same time, if you just want to add right bottom, please use `Orignalbitmap.Height` directly.  
                   Bitmap bmpWithPadding = Bitmap.CreateBitmap(Orignalbitmap.Width + paddingSize, Orignalbitmap.Height + paddingSize, Orignalbitmap.GetConfig());  
                   Canvas canvas = new Canvas(bmpWithPadding);  
                   canvas.DrawColor(Color.White);  
                   //draw it in the top-left corner  
                   canvas.DrawBitmap(Orignalbitmap, 0 ,0, null);  
                  return bmpWithPadding;  
               }  
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful