ansifonts

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 8, 2025 License: MIT Imports: 11 Imported by: 0

README

ansifonts - Go Library for Advanced ANSI Text Rendering

ansifonts is a standalone Go library designed for creating rich, stylized ANSI text in terminal applications. It is the rendering engine for the Bit TUI but is completely independent and can be used in any Go project without requiring TUI dependencies.

The library offers a simple API to render text with 100+ .bit fonts (Bit's own font format based on JSON), advanced typography features, and a wide range of effects, including gradients, shadows, and precise spacing controls.

Features

Feature Description
Font Rendering Render text using a curated collection of over 100 fonts.
Rich Color Support Use any hex color code for text and gradients, providing unlimited color possibilities.
Advanced Text Effects Apply multi-directional gradients and configurable shadows to your text.
Flexible Spacing Controls Fine-tune character, word, and line spacing for precise layout control.
Smart Typography Benefit from advanced kerning and automatic descender alignment.
Text Alignment Align text to the left, center, or right.
Text Scaling Scale text from 0.5x to 4x its original size.
Standalone Library Zero dependencies on the TUI, making it easy to integrate into any Go project.

Quick Start

To get started with the ansifonts library, follow these simple steps:

  1. Install the library:

    go get github.com/superstarryeyes/bit/ansifonts
    
  2. Use it in your Go application:

    package main
    
    import (
        "fmt"
        "log"
    
        "github.com/superstarryeyes/bit/ansifonts"
    )
    
    func main() {
        // Load a font by name
        font, err := ansifonts.LoadFont("8bitfortress")
        if err != nil {
            log.Fatalf("Failed to load font: %v", err)
        }
    
        // Render text with the loaded font
        renderedText := ansifonts.RenderText("Hello", font)
    
        // Print the rendered text
        for _, line := range renderedText {
            fmt.Println(line)
        }
    }
    

Installation

To use the ansifonts library in your project, ensure you have Go 1.25+ installed.

You can add the library to your project as a dependency using go get:

go get github.com/superstarryeyes/bit/ansifonts

Usage

The library provides a flexible API for rendering text. You can perform simple rendering with default settings shown in Quick Start or use the RenderOptions struct for more advanced control.

Advanced Rendering with RenderOptions

For full control over the output, use the RenderTextWithOptions function. This allows you to specify colors, gradients, spacing, alignment, scaling, and shadow effects.

package main

import (
	"fmt"
	"log"

	" github.com/superstarryeyes/bit/ansifonts"
)

func main() {
	font, err := ansifonts.LoadFont("ithaca")
	if err != nil {
		log.Fatalf("Failed to load font: %v", err)
	}

	options := ansifonts.RenderOptions{
		CharSpacing:            4,
		WordSpacing:            4,
		LineSpacing:            1,
		TextColor:              "#FF5733",
		GradientColor:          "#33C3FF",
		UseGradient:            true,
		GradientDirection:      ansifonts.LeftRight,
		Alignment:              ansifonts.LeftAlign,
		ScaleFactor:            1.0,
		ShadowEnabled:          true,
		ShadowHorizontalOffset: 2,
		ShadowVerticalOffset:   1,
		ShadowStyle:            ansifonts.MediumShade,
	}

	rendered := ansifonts.RenderTextWithOptions("Bit\nRender", font, options)
	for _, line := range rendered {
		fmt.Println(line)
	}
}

API Reference

Font Management
  • LoadFont(name string) (*Font, error): Loads a font by its name.
  • ListFonts() ([]string, error): Returns a list of all available font names.
Rendering Functions
  • RenderText(text string, font *Font) []string: Renders text with default settings.
  • RenderTextWithColor(text string, font *Font, colorCode string) []string: Renders text with a specific ANSI color code.
  • RenderTextWithOptions(text string, font *Font, options RenderOptions) []string: Renders text with a full set of custom options.
Core Types
RenderOptions

The RenderOptions struct provides comprehensive configuration for text rendering.

Field Type Description
CharSpacing int Spacing between characters (0 to 10).
WordSpacing int Spacing between words.
LineSpacing int Spacing between lines of multi-line text.
TextColor string Primary text color in hex format (e.g., "#FF0000").
GradientColor string End color for gradients in hex format.
UseGradient bool Enables or disables gradient rendering.
GradientDirection GradientDirection The direction of the gradient (UpDown, DownUp, LeftRight, RightLeft).
Alignment TextAlignment Text alignment (LeftAlign, CenterAlign, RightAlign).
ScaleFactor float64 Scaling factor for the text (e.g., 0.5, 1.0, 2.0).
ShadowEnabled bool Enables or disables the shadow effect.
ShadowHorizontalOffset int Horizontal offset of the shadow in pixels.
ShadowVerticalOffset int Vertical offset of the shadow in pixels.
ShadowStyle ShadowStyle The style of the shadow (LightShade, MediumShade, DarkShade).
Enums

The library uses type-safe enums for alignment, gradient direction, and shadow styles:

  • TextAlignment: LeftAlign, CenterAlign, RightAlign
  • GradientDirection: UpDown, DownUp, LeftRight, RightLeft
  • ShadowStyle: LightShade, MediumShade, DarkShade

Font Collection

The ansifonts library includes over 100 curated bitmap fonts. All fonts are distributed under permissive open-source licenses, which allow free usage, modification, and distribution for both personal and commercial purposes. You can get a complete list of all available fonts using the ListFonts function.

package main

import (
    "fmt"
    "log"

    "github.com/superstarryeyes/bit/ansifonts"
)

func main() {
    fonts, err := ansifonts.ListFonts()
    if err != nil {
        log.Fatalf("Failed to list fonts: %v", err)
    }

    fmt.Println("Available Fonts:")
    for _, fontName := range fonts {
        fmt.Printf("- %s\n", fontName)
    }
}

Examples

The library includes a comprehensive example application that demonstrates various rendering capabilities. To run the application:

cd ansifonts/examples
go run main.go

The examples showcase:

  • Basic text rendering with different fonts
  • Gradient effects with various directions
  • Shadow effects with different styles and offsets
  • Text alignment options
  • Scaling capabilities
  • Custom spacing controls
Library Structure
ansifonts/              # Standalone library package
├── types.go            # Core types, options, and validation
├── loader.go           # Font loading and discovery (with go:embed)
├── renderer.go         # Public rendering API
├── render.go           # Core rendering engine
├── kerning.go          # Advanced kerning with collision detection
├── scaling.go          # ANSI-aware scaling algorithms
├── alignment.go        # Typography alignment and descenders
├── colors.go           # Centralized ANSI color mappings
├── fonts/              # Collection of 100+ .bit font files
└── examples/           # Example application demonstrating library usage
    └── main.go         # Complete example with various rendering options

Contributing

Contributions are welcome. Please feel free to submit issues, feature requests, or pull requests.

License

This project is licensed under the MIT License. See the font files for individual font licenses.

Documentation

Overview

Package ansifonts provides a library for rendering text using ANSI art fonts.

The loader package handles font discovery and loading from the fonts directory.

Package ansifonts provides a library for rendering text using ANSI art fonts.

The renderer package handles text rendering with various formatting options.

Package ansifonts provides a standalone library for rendering text using ANSI art fonts.

The library dynamically discovers ANSI fonts from a fonts directory and provides simple APIs for loading fonts and rendering text with various formatting options.

Basic usage:

font, _ := ansifonts.LoadFont("dogica")
lines := ansifonts.RenderText("Hello", font)
for _, line := range lines {
    fmt.Println(line)
}

Advanced usage with options:

options := ansifonts.RenderOptions{
    CharSpacing: 2,
    TextColor: "#FF0000",
    UseGradient: true,
    GradientColor: "#0000FF",
}
lines := ansifonts.RenderTextWithOptions("Hello", font, options)

Index

Constants

View Source
const (
	MinCharSpacing  = 0
	MaxCharSpacing  = 10
	MinWordSpacing  = 0
	MaxWordSpacing  = 20
	MinLineSpacing  = 0
	MaxLineSpacing  = 10
	MinScaleFactor  = 0.5 // 0.5x
	MaxScaleFactor  = 4.0 // 4x
	MinShadowOffset = -5
	MaxShadowOffset = 5
)

Validation constants for RenderOptions

Variables

View Source
var ANSIColorMap = map[string]string{
	"30": "#000000",
	"31": "#CD3131",
	"32": "#0DBC79",
	"33": "#E5E510",
	"34": "#2472C8",
	"35": "#BC3FBC",
	"36": "#11A8CD",
	"37": "#E5E5E5",
	"90": "#808080",
	"91": "#FF9999",
	"92": "#99FF99",
	"93": "#FFFF99",
	"94": "#66BBFF",
	"95": "#FF99FF",
	"96": "#99FFFF",
	"97": "#FFFFFF",
}

ANSIColorMap provides mappings from ANSI color codes to hex values This is the canonical color mapping used throughout the library

View Source
var EmbeddedFonts embed.FS

Functions

func ApplyHorizontalAlignment

func ApplyHorizontalAlignment(line string, canvasWidth int, alignment HorizontalAlignment) string

ApplyHorizontalAlignment applies horizontal alignment to a single line of text.

func ApplyVerticalAlignment

func ApplyVerticalAlignment(lines []string, canvasHeight int, alignment VerticalAlignment) []string

ApplyVerticalAlignment applies vertical alignment to a set of lines.

func DetectHalfPixelUsage

func DetectHalfPixelUsage(text string, fontData FontData, scaleFactor float64) bool

DetectHalfPixelUsage checks if the current text rendering would use half-pixels that would interfere with shadow rendering. This function should only return true when shadows would actually cause visual artifacts.

func ListFonts

func ListFonts() ([]string, error)

ListFonts returns a list of available font names from both custom and embedded fonts

func RegisterCustomPath added in v0.3.0

func RegisterCustomPath(path string) ([]string, error)

RegisterCustomPath is the smart entry point that handles both files and directories

func RegisterFontDirectory added in v0.3.0

func RegisterFontDirectory(dirPath string) ([]string, error)

RegisterFontDirectory loads all .bit font files from a directory

func RegisterFontFile added in v0.3.0

func RegisterFontFile(path string) (string, error)

RegisterFontFile loads a single .bit font file and registers it

func RenderText

func RenderText(text string, font *Font) []string

RenderText renders text using the specified font with default options

func RenderTextWithColor

func RenderTextWithColor(text string, font *Font, colorCode string) []string

RenderTextWithColor renders text using the specified font and applies ANSI color

func RenderTextWithFont

func RenderTextWithFont(text string, fontData FontData, options RenderOptions) []string

RenderTextWithFont renders text using the specified font with advanced rendering options

func RenderTextWithOptions

func RenderTextWithOptions(text string, font *Font, options RenderOptions) []string

RenderTextWithOptions renders text using the specified font and advanced options

Types

type ColorValidationError

type ColorValidationError struct {
	Field string
	Value string
}

ColorValidationError represents a color validation error

func (*ColorValidationError) Error

func (e *ColorValidationError) Error() string

type DescenderInfo

type DescenderInfo struct {
	HasDescender    bool
	BaselineHeight  int // Height of the main character body (excluding descender)
	DescenderHeight int // Height of the descender part
	TotalHeight     int // Total character height
	VerticalOffset  int // How much to offset this character vertically
}

DescenderInfo holds information about a character's descender properties

type Font

type Font struct {
	Name     string
	FontData FontData
}

Font represents a loaded font with its metadata

func LoadFont

func LoadFont(name string) (*Font, error)

LoadFont loads a font by name, checking custom fonts first, then embedded fonts

type FontData

type FontData struct {
	Name       string              `json:"name"`
	Author     string              `json:"author"`
	License    string              `json:"license"`
	Characters map[string][]string `json:"characters"`
}

FontData represents the overall structure of our .bit font file (JSON format)

type GradientDirection

type GradientDirection int

GradientDirection represents gradient direction options

const (
	UpDown GradientDirection = iota
	DownUp
	LeftRight
	RightLeft
)

type HorizontalAlignment

type HorizontalAlignment int

HorizontalAlignment represents the horizontal alignment of a character or line.

const (
	// AlignLeft aligns the left of the character/line to the left of the canvas.
	AlignLeft HorizontalAlignment = iota
	// AlignCenter aligns the center of the character/line to the center of the canvas.
	AlignCenter
	// AlignRight aligns the right of the character/line to the right of the canvas.
	AlignRight
)

type RenderOptions

type RenderOptions struct {
	// Spacing options
	CharSpacing int // Character spacing (0 to 10)
	WordSpacing int // Word spacing (0 to 20)
	LineSpacing int // Line spacing (0 to 10)

	// Text alignment
	Alignment TextAlignment

	// Text color options
	TextColor         string // Hex color code (e.g., "#FFFFFF")
	GradientColor     string // Hex color code for gradient end color
	GradientDirection GradientDirection
	UseGradient       bool

	// Text scale
	ScaleFactor float64 // 0.5: half size, 1.0: normal, 2.0: double, 4.0: quadruple

	// Shadow options
	ShadowEnabled          bool
	ShadowHorizontalOffset int // -5 to 5
	ShadowVerticalOffset   int // -5 to 5
	ShadowStyle            ShadowStyle

	// Multi-line text
	TextLines []string
}

RenderOptions contains all the options for rendering text

func DefaultRenderOptions

func DefaultRenderOptions() RenderOptions

DefaultRenderOptions returns RenderOptions with default values

func (*RenderOptions) Validate

func (opts *RenderOptions) Validate() error

Validate checks if the RenderOptions are valid and returns an error if not

type ScaleValidationError

type ScaleValidationError struct {
	Field string
	Value float64
	Min   float64
	Max   float64
}

ScaleValidationError represents a scale validation error

func (*ScaleValidationError) Error

func (e *ScaleValidationError) Error() string

type ShadowStyle

type ShadowStyle int

ShadowStyle represents shadow style options

const (
	LightShade ShadowStyle = iota
	MediumShade
	DarkShade
)

type ShadowStyleOption

type ShadowStyleOption struct {
	Name string
	Char rune
	Hex  string
}

ShadowStyleOption represents shadow style options

type TextAlignment

type TextAlignment int

TextAlignment represents text alignment options

const (
	LeftAlign TextAlignment = iota
	CenterAlign
	RightAlign
)

type ValidationError

type ValidationError struct {
	Field string
	Value int
	Min   int
	Max   int
}

ValidationError represents a validation error for RenderOptions

func (*ValidationError) Error

func (e *ValidationError) Error() string

type VerticalAlignment

type VerticalAlignment int

VerticalAlignment represents the vertical alignment of a character or line.

const (
	// AlignTop aligns the top of the character/line to the top of the canvas.
	AlignTop VerticalAlignment = iota
	// AlignMiddle aligns the middle of the character/line to the middle of the canvas.
	AlignMiddle
	// AlignBottom aligns the bottom of the character/line to the bottom of the canvas.
	AlignBottom
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL