Android Code Snippet Scale image

SubName: ScaleImage

Description:
Scales the view V to the correct aspect ratio to view on the devices screen size based on the dimentions of the drawable Bmd.

B4X:
Public Sub ScaleImage(Bmd As BitmapDrawable, V As View)
   Dim bmp As Bitmap
   Dim hgt, wid As Int
   Dim scale As Float
   Dim ls As Boolean
   Dim cw, ch As Int
 
   wid = Activity.width
   hgt = Activity.height
 
   ls = wid > hgt
   bmp = Bmd.Bitmap
   scale = bmp.width / bmp.height
 
   If ls Then
   cw = hgt * scale
   ch = hgt
   Else
   cw = wid
   ch = wid * scale
   End If
 
   V.width = cw
   V.height = ch
 
End Sub

With modifications, this routine can be used for about any app. If you don't want it to use the size of the device screen, modify the code to take the view size instead of the activity.

Tags: Scale,Image

--- Jem
 

HotShoe

Well-Known Member
Licensed User
Longtime User
this is a bump for this routine. I have seen it asked a few times lately in the chat as well as the forum.

--- Jem
 

sorex

Expert
Licensed User
Longtime User
thanks Shoe, for the hint on the command below. didn't know that was possible without an if/then statement (it prolly gets converted to one I guess)

B4X:
ls = wid > hgt
 

bluejay

Active Member
Licensed User
Longtime User
Good Idea HotShoe.

It could also be simplified to:

B4X:
Public Sub ScaleImage(Bmd As BitmapDrawable, V As View)
  Dim hgt, wid As Int

  wid = Activity.width
  hgt = Activity.height
  If wid > hgt Then
    V.width  = hgt * (Bmd.Bitmap.width / Bmd.Bitmap.height)
    V.height = hgt
  Else
    V.width  = wid
    V.height = wid * (Bmd.Bitmap.width / Bmd.Bitmap.height)
  End If

End Sub
 

HotShoe

Well-Known Member
Licensed User
Longtime User
Yeah I did it long hand to make it easier to understand. I did forget the ls = wid > hgt bit though hehe. Old habits die hard, but I try to not use shortcuts in examples.

--- Jem
 
Top