LogoLogo
  • Gum Tool
    • Introduction
    • Setup
      • Running from Source
    • Showcase
    • Tutorials and Examples
      • Intro Tutorials
        • 1 - The Basics
        • 2 - Variables Tab
        • 3 - Files
        • 4 - Components
        • 5 - Exposing Variables
        • 6 - Parent
        • 7 - States
        • 8 - State Categories
      • Animation Tutorials
        • 1 - Introduction to Animation
        • 2 - Creating an Animation
        • 3 - Playing Animations inside other Animations
        • 4 - Combining Multiple Categories
      • Examples
        • Bottom-Up Stack
        • Centering
        • Custom NineSlice
        • Health Bar
        • Padding
    • Gum Elements
      • General Properties
        • Alpha
        • Base Type (Inheritance)
        • Blend
        • Clips Children
        • Has Events
        • Height Units
        • Ignored By Parent Size
        • Locked
        • Max Height
        • Max Width
        • Min Height
        • Min Width
        • Order
        • Parent
        • Rotation
        • Visible
        • Variable References
        • Width Units
        • X
        • X Origin
        • X Units
        • Y
        • Y Origin
        • Y Units
      • Behaviors
        • Default Implementation
      • Circle
      • ColoredRectangle
      • Component
        • Default Child Container
      • Container
        • Children Layout
        • Contained Type
        • Is Render Target
        • Stack Spacing
        • Wraps Children
      • NineSlice
        • Blend
        • Custom Frame Texture Coordinate Width
        • Texture Address
        • Texture Left
        • Texture Top
      • Polygon
        • Points
      • Skia Standard Elements
        • General Properties
          • Has Dropshadow
          • Is Filled
          • Use Gradient
        • Arc
          • Start Angle
          • Sweep Angle
          • Thickness
        • Canvas
        • ColoredCircle
        • LottieAnimation
        • RoundedRectangle
          • Corner Radius
        • Svg
      • Sprite
        • Color
        • Source File
        • Texture Address
        • Wrap
      • States
        • Categories
      • Text
        • Blue
        • Color
        • Font
        • Font Scale
        • Font Size
        • Green
        • Is Bold
        • Is Italic
        • MaxLettersToShow
        • Outline Thickness
        • Red
        • Text
        • Text Overflow Horizontal Mode
        • Text Overflow Vertical Mode
        • Use Custom Font
        • Use Font Smoothing
    • Project Tab
    • Code Tab
      • Runtime Generation Details
      • Generation Scope
      • Inheritance Location
      • Is CodeGen Plugin Enabled
      • Show CodeGen Preview
    • Localization
    • Menu
      • Content
      • Project Properties
    • Plugins
      • AddAndRemoveVariablesForType
      • AddMenuItem
      • Export
      • Setting Up Post Build Events
    • Variables
      • Add Variable
    • Bitmap font generator (.fnt)
    • Upgrading
      • Migrating to 2025 June Preview
      • Migrating to 2025 May 28
      • Breaking Changes
        • Removal of Variable Spaces
  • Code
    • Gum Code Reference
      • AnimationRuntime
      • BitmapCharacterInfo
      • BitmapFont
      • Camera
      • CircleRuntime
      • ColoredRectangleRuntime
      • Component Runtimes
      • ContainerRuntime
      • Cursor
      • Gum Class Overview
      • DataUiGrid
        • Reflection
        • Categories
      • ElementSave
        • ToGraphicalUiElement
      • GraphicalUiElement
        • Absolute Values
        • AddToManagers
        • AnimateSelf
        • ApplyState
        • BlendState
        • CanvasHeight
        • CanvasWidth
        • Children
        • ContainedElements
        • Font Values
        • GetAbsoluteHeight
        • GetAbsoluteWidth
        • GetChildByNameRecursively
        • GetFrameworkElementByName
        • IsAllLayoutSuspended
        • Parent
        • ParentChanged
        • RemoveFromManagers
        • UpdateLayout
      • GumProjectSave
      • IDataUi
      • InstanceMember
      • InstanceSave
      • InteractiveGue
        • CurrentInputReceiver
        • RaiseChildrenEventsOutsideOfBounds
        • RollOverBubbling
      • IPositionedSizedObject
      • Layer
      • NineSliceRuntime
      • RectangleRuntime
      • Renderer
        • SinglePixelTexture
      • SelectedState
      • SpriteRenderer
        • LastFrameDrawStates
      • SpriteRuntime
        • TextureAddress
        • TextureHeight
        • TextureLeft
        • TextureTop
        • TextureWidth
      • TextRuntime
        • Color
        • FontScale
        • FontSize
        • HorizontalAlignment
        • Text Wrapping
        • VerticalAlignment
      • VariableSave
    • FNA
    • Kni
    • Meadow
    • MonoGame
      • Setup
        • Linking Game Project to Source (Optional)
      • Tutorials
        • Gum Project Forms Tutorial
          • Setup
          • Gum Screens
          • Common Component Types
          • Styling
          • Multiple Screens
        • Code-Only Gum Forms Tutorial
          • Setup
          • Forms Controls
          • ListBox Items
          • Input in Forms
        • [Deprecated] Gum Project (.gumx) Tutorial
          • Setup
          • Gum Screens
          • Gum Forms
          • Customizing Forms
          • Strongly Typed Components Using Code Generation
          • Multiple Screens
      • Setup for GumBatch (Optional)
      • Loading a Gum Project (Optional)
      • async Programming
      • Custom Runtimes
      • GumBatch
      • Gum Forms
        • Binding (ViewModels)
        • Controls
          • Button
          • CheckBox
          • FrameworkElement
            • BindingContext
            • IsEnabled
            • IsFocused
            • ModalRoot and PopupRoot
            • SetBinding
          • Label
          • ListBox
          • ListBoxItem
          • MenuItem
          • PasswordBox
          • RadioButton
          • ScrollViewer
            • VerticalScrollBarValue
          • StackPanel
          • Slider
          • TextBox
          • Window
        • Control Customization In Code
          • MenuItem
          • TextBox
        • Control Customization in Gum Tool
        • Gamepad Support
        • Keyboard Support
        • Troubleshooting
      • File Loading
      • Profiling
      • Resizing the Game Window
      • Known Issues
      • Samples
        • MonoGameGumFormsSample
    • Nez
    • Silk.NET
    • SkiaGum
      • Setup
        • WPF
    • .NET MAUI
      • Setup
        • SkiaGumCanvasView
Powered by GitBook
On this page
  • Introduction
  • Example - Creating a TextRuntime
  • Example - Obtaining a TextRuntime Reference From a Gum Project
  • Fonts
  • Assigning CustomFontFile
  • Assigning BitmapFont
  • Font Component Values
  • Creating Fonts
  • Missing Font Exceptions

Was this helpful?

Edit on GitHub
Export as PDF
  1. Code
  2. Gum Code Reference

TextRuntime

Introduction

The TextRuntime object is used to draw strings to the screen. It supports a variety of options for rendering text including alignment, fonts, coloring, and line wrapping.

Example - Creating a TextRuntime

To create a TextRuntime, instantiate it and add it to the managers as shown in the following code:

var textInstance = new TextRuntime();
textInstance.Text = "Hello world";
textInstance.AddToRoot();

Usually TextRuntime instances are created and added to children such as a StackPanel or the visual of a component as shown in the following code:

var textInstance = new TextRuntime();
textInstance.Text = "Hello world";
MainStackPanel.AddChild(textInstance);

Example - Obtaining a TextRuntime Reference From a Gum Project

To get a TextRuntime instance from a loaded Gum (gumx) project, add the following code. This code assumes you have an object named CurrentScreen, and that it contains a Text instance named TextInstance:

var textInstance = (TextRuntime)CurrentScreen.GetGraphicalUiElementByName("TextInstance");
textInstance.Text = "I've been modified in code";

Fonts

By default all TextRuntime instances use an Arial 18 pt font. This can be changed by specifying ta custom font.

Fonts on TextRuntime objects can be modified in one of the following ways:

  1. By setting the UseCustomFont property to true, then changing the CustomFontFile property to a desired .fnt file.

  2. By directly assigning the BitmapFont property on the TextRuntime object, bypassing all other properties.

  3. By setting UseCustomFont property to false, then changing the individual Font values. This approach requires following a specific .fnt naming convention.

For most projects, the first approach is recommended since it doesn't require specific naming conventions. The second approach also works well if you are directly loading the BitmapFont object yourself. The third approach is convenient if your project is using the Gum tool, and if the Gum tool has already generated fonts for the specific combinations of values you are assigning.

Assigning CustomFontFile

The following code shows how to load a custom font (the first approach):

var customText = new TextRuntime();
customText.UseCustomFont = true;
customText.CustomFontFile = "WhitePeaberryOutline/WhitePeaberryOutline.fnt";
customText.Text = "Hello, I am using a custom font";
customText.AddToManagers(SystemManagers.Default, null);

Note that .fnt files reference one or more image files, so the image file must also be added to the correct folder. In this case, the WhitePeaberryOutline.fnt file references a WhitePeaberryOutline.png file, so both files are in the same folder.

Also, note that files are loaded from-file rather than using the content pipeline. This means that extensions (such as .fnt) are included in the file path, and that both the .fnt and .png files must have their Copy to Output Directory value set to Copy if newer.

Assigning BitmapFont

The following code shows how to assign the BitmapFont property on a TextRuntime:

var bitmapFont = new BitmapFont("WhitePeaberryOutline/WhitePeaberryOutline.fnt", SystemManagers.Default);
customText.BitmapFont = bitmapFont;
// no additional properties such as UseCustomFont or any of the font component values
// are used once this is assigned. By assigning those, the BitmapFont assignment may
// get overwritten

Font Component Values

A TextRuntime's font can be controlled by its individual font component values. Setting these values in code will not produce a .fnt file for you - the .fnt file must already be in your project in the FontCache folder. The following values are used to determine the font (.fnt) to load:

  • FontSize

  • Font

  • OutlineThickness

  • UseFontSmoothing

  • IsItalic

  • IsBold

By default, all fonts will be of the format Font{Font}{FontSize}.fnt. Consider the following code:

text.UseCustomFont = false;
text.Font = "Arial";
text.FontSize = 24;

This results in the TextRuntime object searching for a font named FontArial24.fnt.

The following additional suffixes (in order listed below) are added to the font name.

  • OutlineThicknes - if greater than 0, then the suffix _o followed by the outline thickness is added. For example, if OutlineThickness is 3, a font might be named FontArial24_3.fnt

  • UseFontSmoothing - if false, then _noSmooth is appended. For example Font24_noSmooth.fnt

  • IsItalic - if true, then _Italic is appended. For example Font24_Italic.fnt

  • IsBold - if true, then _Bold is appended. For example Font24_Bold.fnt

The BmfcSave.GetFontCacheFileNameFor method can be called with any combination to obtain the desired font value. For example, the following code coudl be used to determine the desired .fnt file:

var desiredFntName = BmfcSave.GetFontCacheFileNameFor(
    18, // font size
    "Consolas", // font name
    2, // outline thickness
    true, // use font smoothing
    false, // is italic
    true // is bold
    );

Note that this method does not take into consideration the content folder.

Creating Fonts

To create a .fnt file, you have a few options:

  1. Open Gum, create a temporary Text instance with the desired properties, then look at the font cache folder

  2. Manually create a .fnt file in a text editor and a corresponding .png. This option requires understanding how the .fnt file format is structured. The best way to learn this is to open an existing font file.

Using Gum to create the font cache is fairly simple, but you must know which fonts you intend to use ahead of time. A font is created automatically by the Gum tool whenever a Text property is changed.

To view the existing font cache, you can click the View Font Cache menu item in Gum.

As you make changes to the Text object, new files are created and added to the font cache folder, as shown in the following animation:

Missing Font Exceptions

By default TextRuntime instances do not throw exceptions for missing font files even if GraphicalUiElement.ThrowExceptionsForMissingFiles is set to CustomSetPropertyOnRenderable.ThrowExceptionsForMissingFiles. The reason for this is because a TextRuntime's font is decided by a combination multiple properties.

If UseCustomFont is set to false, then the font is determined by the combination of font values (as discussed above). If UseCustomFont is set to true, then the font is determined by the CustomFontFile (also as discussed above).

Ultimately the variables which are used for fonts can be assigned in any order, and can be assigned from multiple spots (such as direct assignments, states, or creation from Gum projects).

In other words, the TextRuntime doesn't know when variable assignment is finished. We can address this in a few different ways.

The first is to explicitly load the desired BitmapFont as discussed above. By calling the BitmapFont constructor, missing files will immediately throw an exception.

Another option is to use the GraphicalUiElement.ThrowExceptionsForMissingFiles method to verify if a font is valid.

The following code example shows how to check for invalid fonts using this method:

var textWithValidFont = new TextRuntime();
textWithValidFont.UseCustomFont = true;
textWithValidFont.CustomFontFile = "Fonts/ValidFont.fnt";
textWithValidFont.AddToManagers(SystemManagers.Default, null);
// No errors here:
GraphicalUiElement.ThrowExceptionsForMissingFiles(text3);

try
{
    var textThatHasError = new TextRuntime();
    textThatHasError.UseCustomFont = true;
    textThatHasError.CustomFontFile = "Fonts/InvalidFont.fnt";
    textWithValidFont.AddToManagers(SystemManagers.Default, null);
    GraphicalUiElement.ThrowExceptionsForMissingFiles(textThatHasError);
}
catch (FileNotFoundException e)
{
    System.Diagnostics.Debug.WriteLine("Yay we got an exception! That's expected");     
}
PreviousTextureWidthNextColor

Last updated 1 month ago

Was this helpful?

For information on creating your own .fnt file with Bitmap Font Generator, see the page.

This code assumes a font file named WhitePeaberryOutline.fnt is located in the Content/WhitePeaberryOutline folder. By default all Gum content loading is performed relative to the Content folder; however, if UseCustomFont is set to false, then all font loading is performed from the FontCache folder. See the section for more information on loading from the FontCache folder. See the page for more information about loading files in general.

The easiest way to mark all content as "Copy to Output Directory" is to use wildcard items in your .csproj. This is explained in the page.

As mentioned before, when UseCustomFont is set to false the Gum runtime looks for the font in the FontCache folder. For this particular example the font would be located at Content/FontCache/FontArial24.fnt. Note that if your Gum project is not located at the content root, then your FontCache folder will not be directly in the Content folder either. To fix this problem using the FileManager's RelativeDirectory, see the page.

Use Angelcode Bitmap Font Generator. For more information see the .

Use Custom Font
Font Component Values
File Loading
Loading .gumx (Gum project)
File Loading
Use Custom Font page
WhitePeaberryOutline font in the Solution Explorer
Copy if newer property set
View Font Cache menu item
Changing the Font Size creates new fonts in FontCache