Android Tutorial [B4X] [XUI] Drawing with B4XCanvas

Discussion in 'Tutorials & Examples' started by Erel, Oct 17, 2017.

  1. Erel

    Erel Administrator Staff Member Licensed User

    B4XCanvas is the cross platform version of Canvas.

    Steps to using B4XCanvas:

    1. Initialize and pass the target view. In most cases it will be a Panel (or Pane). It must be a Pane in B4J.
    2. Make the drawings.
    3. Call Invalidate to commit the drawings.
    4. If the target view is resized then you should call B4XCanvas.Resize. This is more relevant in B4J and B4i as the activity is recreated in B4A when the screen size changes.
    5. B4XCanvas.CreateBitmap returns the drawings bitmap.
    6. Call B4XCanvas.Release if the canvas is no longer required.

    Example of a bouncing smiley:

    [​IMG]

    Code:
    Sub Process_Globals
       
    Private Timer1 As Timer
    End Sub

    Sub Globals
       
    Private xui As XUI
       
    Private smiley As B4XBitmap
       
    Private deg, vx = 10dip, vy = 10dip As Double
       
    Private SmileyRect As B4XRect
       
    Private size As Double = 40dip
       
    Private Panel1 As B4XView
       
    Private cvs As B4XCanvas

    End Sub

    Sub Activity_Create(FirstTime As Boolean)
       
    Activity.LoadLayout("1")
       Create
    End Sub

    '*** code is identical from here ***
    Sub Resize 'ignore
       cvs.Resize(Panel1.Width, Panel1.Height)
       cvs.ClearRect(cvs.TargetRect)
       cvs.Invalidate
    End Sub

    Sub Create
       smiley = xui.LoadBitmapResize(
    File.DirAssets, "smiley.png", size, size, False)
       
    If xui.IsB4J Then
         vx = 
    7dip
         vy = 
    7dip
       
    Else
         vx = 
    10dip
         vy = 
    10dip
       
    End If
       Timer1.Initialize(
    "Timer1"10)
       Timer1.Enabled = 
    True
       SmileyRect.Initialize(
    10dip10dip10dip + size, 10dip + size)
       cvs.Initialize(Panel1)
    End Sub

    Sub Timer1_Tick
       cvs.ClearRect(cvs.TargetRect)
       
    If SmileyRect.Right > cvs.TargetRect.Width Then
         vx = -
    Abs(vx)
       
    Else If SmileyRect.Left < 0 Then
         vx = 
    Abs(vx)
       
    End If
       
    If SmileyRect.Bottom > cvs.TargetRect.Height Then
         vy = -
    Abs(vy)
       
    Else If SmileyRect.Top < 0 Then
         vy = 
    Abs(vy)
       
    End If
       SmileyRect.Left = SmileyRect.Left + vx
       SmileyRect.Top = SmileyRect.Top + vy
       SmileyRect.Width = size
       SmileyRect.Height = size
       deg = deg + 
    1
       cvs.DrawBitmapRotated(smiley, SmileyRect, deg)
       cvs.Invalidate
    End Sub
    Another example: [B4X] [XUI] Create a round image
     

    Attached Files:

    Last edited: Oct 24, 2017
Loading...
  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