Android Code Snippet [B4X] [BitmapCreator] Find Minimum Bounding Rectangle

Input: A Bitmap or B4XBitmap.

Output: A rectangle with the boundaries of the non-transparent area.

B4X:
Sub FindMinRect (bmp As B4XBitmap) As B4XRect
   Dim bc As BitmapCreator
   bc.Initialize(bmp.Width, bmp.Height)
   bc.CopyPixelsFromBitmap(bmp)
   Dim r As B4XRect
   r.Initialize(bc.mWidth / 2, -1, bc.mWidth / 2, 0)
   For y = 0 To bc.mHeight - 1
       For x = 0 To bc.mWidth - 1
           If bc.IsTransparent(x, y) = False Then
               r.Left = Min(r.Left, x)
               Exit
           End If
       Next
       If x < bc.mWidth Then
           If r.Top = -1 Then
               r.Top = y
           Else
               r.Bottom = y + 1
           End If
           For x = bc.mWidth - 1 To 0 Step -1
               If bc.IsTransparent(x, y) = False Then
                   r.Right = Max(r.Right, x + 1)
                   Exit
               End If
           Next
       End If
   Next
   Return r
End Sub

Usage:
B4X:
Dim r As B4XRect = FindMinRect(bmp)
ImageView2.SetBitmap(bmp.Crop(r.Left, r.Top, r.Width, r.Height))

Depends on: XUI and BitmapCreator libraries.
 
Last edited:

asales

Expert
Licensed User
Longtime User
I don't understand what this function do.
I tried to use it, but I don't saw an image in output.
Can you put an image of output to ilustrate?
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…