Android Code Snippet Drawing Multiline Text

Discussion in 'Code Snippets' started by Erel, Mar 18, 2019.

  1. Erel

    Erel Administrator Staff Member Licensed User

    This code creates a label with the text and returns a snapshot of the label:

    Code:
    Sub TextToBitmap (Width As Int, Fnt As B4XFont, Clr As Int, Text As StringAs B4XBitmap
       
    Dim lbl As Label
       lbl.Initialize(
    "")
       
    Dim x As B4XView = lbl
       x.Font = Fnt
       x.TextColor = Clr
       x.SetLayoutAnimated(
    000, Width, 0)
       
    Dim su As StringUtils
       x.Height = su.MeasureMultilineTextHeight(x, Text)
       x.Text = Text
       
    Return x.Snapshot
    End Sub
    Depends on: XUI, StringUtils

    Usage example of drawing multiline text on a PDF document (Printing library):
    Code:
    Sub Process_Globals
       
    Private rp As RuntimePermissions
       
    Private xui As XUI
    End Sub

    Sub Globals

    End Sub

    Sub Activity_Create(FirstTime As Boolean)
       rp.CheckAndRequest(rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
       
    Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
       
    If Result Then
           
    Dim pdf As PdfDocument
           pdf.Initialize
           pdf.StartPage(
    595842'A4 size
           Dim bmp As B4XBitmap = TextToBitmap(200dip, xui.CreateDefaultBoldFont(20), xui.Color_Black, _
            
    $"s dflkj sdfkls
    dffwje klfj wlkef jwlke fjlwkef jklwe jflkwe jflkwe jflkwe jflkwe jfl
    sdf
    we
     gfkwe lg;kw e;lg wklelg; weg wel;g"$
    )
             
    Dim rect As Rect
           
    rect.Initialize(303000)
           
    rect.Width = bmp.Width / bmp.Scale
           
    rect.Height = bmp.Height / bmp.Scale
           pdf.Canvas.DrawBitmap(bmp, 
    Nullrect)
           pdf.FinishPage
           
    Dim out As OutputStream = File.OpenOutput(File.DirRootExternal, "1.pdf"False)
           pdf.WriteToStream(out)
           out.Close
           pdf.Close
       
    End If
    End Sub
     
    SJQ, jimmyF, Filippo and 4 others like this.
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