B4J Code Snippet [B4X][XUI] Fill and Fit images without distortion

Discussion in 'B4J Code Snippets' started by Erel, Nov 28, 2017.

  1. Erel

    Erel Administrator Staff Member Licensed User

    Fit = Resize the image to the container size while preserving the image ratio. Leaves empty space if the image aspect ratio is different than the container aspect ratio.

    Fill (without distortion) = Crops the image to make it with the same aspect ratio as the container aspect ratio and then resizes the image.

    Example of fit:


    Example of fill:


    Sub FitImageToView(bmp As B4XBitmap, ImageView As B4XView)
    'this sub is not really needed
       ImageView.SetBitmap(bmp.Resize(ImageView.Width, ImageView.Height, True))
    End Sub

    Sub FillImageToView(bmp As B4XBitmap, ImageView As B4XView)
    Dim bmpRatio As Float = bmp.Width / bmp.Height
    Dim viewRatio As Float = ImageView.Width / ImageView.Height
    If viewRatio > bmpRatio Then
    Dim NewHeight As Int = bmp.Width / viewRatio
         bmp = bmp.Crop(
    0, bmp.Height / 2 - NewHeight / 2, bmp.Width, NewHeight)
    Else if viewRatio < bmpRatio Then
    Dim NewWidth As Int = bmp.Height * viewRatio
         bmp = bmp.Crop(bmp.Width / 
    2 - NewWidth / 20, NewWidth, bmp.Height)
    End If
    ImageView.SetBitmap(bmp.Resize(ImageView.Width, ImageView.Height, True))
    End Sub
    Usage example (B4J):
    Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Private xui As XUI '<-------------
       Private ImageView1 As ImageView
    End Sub

    Sub AppStart (Form1 As Form, Args() As String)
       MainForm = Form1
    Dim bmp As B4XBitmap = xui.LoadBitmap(File.DirAssets, "image.png")
       FillImageToView(bmp, ImageView1)
    End Sub
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice