Games [XUI2D] Large background class + example

Erel

B4X founder
Staff member
Licensed User
Longtime User
LargeBackground class helps with drawing the game background based on a large image that is split into smaller images.

The first step is to split the large image. You can do it in any way you like, including with this B4J code:
B4X:
Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Private xui As XUI
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.RootPane.LoadLayout("Layout1")
    MainForm.Show
    Dim bmp As B4XBitmap = xui.LoadBitmap("C:\Users\H\Downloads\mapa.gif", "")
    Split(bmp, 7, 14)
End Sub

Sub Split(bmp As B4XBitmap, Rows As Int, Columns As Int)
    Dim RowHeight As Int = bmp.Height / Rows
    Dim ColumnWidth As Int = bmp.Width / Columns
    For r = 0 To Rows - 1
        For c = 0 To Columns - 1
            Dim b As B4XBitmap = bmp.Crop(ColumnWidth * c, bmp.Height - RowHeight * (r + 1), ColumnWidth, RowHeight)
            Dim out As OutputStream = File.OpenOutput("C:\Users\H\Downloads", $"map_${c}x${r}.png"$, False) 'change folder
            b.WriteToStream(out, 100, "PNG")
            out.Close
        Next
    Next
End Sub
The result:

1623592548376.png

Note that map_0x0 is the bottom-left corner.

The split images should be put in the Shared Files folder.
The code itself is very simple:
B4X:
Background.Initialize(Me, "map", "png", TotalWidth, TotalHeight, 7, 14)
"map" - the files prefix
"png" - the files extension
TotalWidth / TotalHeight - Complete game width/height in meters
7 - Number of rows
14 - Number of columns

Call Background.Tick from the Tick event:
B4X:
Background.Draw(GS)

And DrawComplete from the DrawingComplete event:
B4X:
Public Sub DrawingComplete
    Background.DrawComplete
End Sub

Note that ivBackground should be public variable.

The example shows this map: https://opengameart.org/content/fantasy-world-map
The complete map size is 8000x4000.

1623591988553.png


The LargeBackground class is included in the example.
 
Last edited:

Erel

B4X founder
Staff member
Licensed User
Longtime User
Class was updated. It now draws on a background layer (ivBackground). This provides more options for optimizations.

There are two configurable parameters inside the class:
UpdateInterval - Drawing will happen every interval. Default value is 1 which means that the background is updated every step.
BackgroundExtraScale - Scales down the tiles. Default value is 1.5. 1 = no scaling.
 

sorex

Expert
Licensed User
Longtime User
do you have a doughnut addiction, Erel? I've seen that one passing by before.
 
Top