Search code examples
garminconnectiq

How to format and display long text using Garmin ConnectIQ SDK


I'm trying to display a message which may be longer than screen width. What's the best way to format the message to display it as multiline?

Note, that the messages comes from server, so it's not a hardcoded resource string.

I cannot see any tools for that, and neither Toybox::WatchUi::Text drawable nor Dc.drawText seem to have support for paragraph formatting.

Dc.getTextDimensions allows to determine width and height of text, so this is potentially helpful, but native apps (e.g. message notifier) do display properly formatted paragraphs, so I have an impression I'm missing something.


Solution

  • Since API Level 3.1.0 there is very appealing fitTextToArea() which can be used to get a text string to fit in a specified area.

    Parameters:

    • text — (Lang.String) — The text to fit into the given area, which may include newlines
    • font — (Graphics.FontType) — The font to use when determining line break placement
    • width — (Lang.Number) — The width of the area to fit within
    • height — (Lang.Number) — The height of the area to fit within
    • truncate — (Lang.Boolean) — If true, the resulting string may be truncated to fit within the provided area using the provided font

    Returns:

    Returns a String suitable for display in the given area. The String will be truncated if the truncate parameter is true and the String cannot fit into the specified area. Otherwise, null will be returned.

    For example:

    //! Draw the item's label and bitmap
    //! @param dc Device context
    public function draw(dc as Dc) as Void {
        var font = Graphics.FONT_XTINY;
    
        dc.setColor(Graphics.COLOR_DK_GRAY, Graphics.COLOR_TRANSPARENT);
        dc.drawText(dc.getWidth() / 2,
                    dc.getHeight() / 2,
                    font,
                    Graphics.fitTextToArea(_description, font, dc.getWidth()-10, dc.getHeight(), true),
                    Graphics.TEXT_JUSTIFY_CENTER | Graphics.TEXT_JUSTIFY_VCENTER);
    }
    

    Reference