github.com/racerxdl/gonx@v0.0.0-20210103083128-c5afc43bcbd2/font/font.go (about)

     1  package font
     2  
     3  import (
     4  	"image/color"
     5  	"strings"
     6  	"unsafe"
     7  )
     8  
     9  // Generate all font files from bdf in this folder
    10  //go:generate go run generate.go
    11  
    12  type Glyph struct {
    13  	Name string
    14  	Data [][]byte
    15  }
    16  
    17  func (g *Glyph) DrawAt(x, y int, c color.RGBA, pixels []byte, imgWidth int) {
    18  	u32color := (uint32(c.A) << 24) + (uint32(c.B) << 16) + (uint32(c.G) << 8) + uint32(c.R)
    19  	p := y*imgWidth + x
    20  
    21  	rows := len(g.Data)
    22  	columns := len(g.Data[0])
    23  
    24  	for cy := 0; cy < rows; cy++ {
    25  		row := g.Data[cy]
    26  		for cx := 0; cx < columns; cx++ {
    27  			if row[cx] > 0 {
    28  				cp := p + cx + cy*imgWidth
    29  				*(*uint32)(unsafe.Pointer(&pixels[cp*4])) = u32color
    30  			}
    31  		}
    32  	}
    33  }
    34  
    35  type Data struct {
    36  	CharWidth  int
    37  	CharHeight int
    38  	XOffset    int
    39  	YOffset    int
    40  	Glyphs     map[uint32]*Glyph
    41  }
    42  
    43  var defaultGlyph = &Glyph{
    44  	Name: "EMPTY SPACE",
    45  	Data: [][]byte{
    46  		{0, 0, 0, 0, 0, 0, 0, 0},
    47  		{0, 0, 0, 0, 0, 0, 0, 0},
    48  		{0, 0, 0, 0, 0, 0, 0, 0},
    49  		{0, 0, 0, 0, 0, 0, 0, 0},
    50  		{0, 0, 0, 0, 0, 0, 0, 0},
    51  		{0, 0, 0, 0, 0, 0, 0, 0},
    52  		{0, 0, 0, 0, 0, 0, 0, 0},
    53  		{0, 0, 0, 0, 0, 0, 0, 0},
    54  		{0, 0, 0, 0, 0, 0, 0, 0},
    55  		{0, 0, 0, 0, 0, 0, 0, 0},
    56  		{0, 0, 0, 0, 0, 0, 0, 0},
    57  		{0, 0, 0, 0, 0, 0, 0, 0},
    58  		{0, 0, 0, 0, 0, 0, 0, 0},
    59  		{0, 0, 0, 0, 0, 0, 0, 0},
    60  		{0, 0, 0, 0, 0, 0, 0, 0},
    61  	},
    62  }
    63  
    64  func (d *Data) GetGlyph(unicode uint32) *Glyph {
    65  	if glyph, ok := d.Glyphs[unicode]; ok {
    66  		return glyph
    67  	}
    68  
    69  	return defaultGlyph
    70  }
    71  
    72  var fonts = map[string]*Data{}
    73  
    74  func GetFontByName(name string) *Data {
    75  	name = strings.ToLower(name)
    76  	if font, ok := fonts[name]; ok {
    77  		return font
    78  	}
    79  
    80  	return nil
    81  }