github.com/Seikaijyu/gio@v0.0.1/text/text.go (about)

     1  // SPDX-License-Identifier: Unlicense OR MIT
     2  
     3  package text
     4  
     5  import (
     6  	"fmt"
     7  
     8  	"github.com/Seikaijyu/gio/io/system"
     9  	"golang.org/x/image/math/fixed"
    10  )
    11  
    12  type Alignment uint8
    13  
    14  const (
    15  	Start Alignment = iota
    16  	End
    17  	Middle
    18  )
    19  
    20  func (a Alignment) String() string {
    21  	switch a {
    22  	case Start:
    23  		return "Start"
    24  	case End:
    25  		return "End"
    26  	case Middle:
    27  		return "Middle"
    28  	default:
    29  		panic("invalid Alignment")
    30  	}
    31  }
    32  
    33  // Align returns the x offset that should be applied to text with width so that it
    34  // appears correctly aligned within a space of size maxWidth and with the primary
    35  // text direction dir.
    36  func (a Alignment) Align(dir system.TextDirection, width fixed.Int26_6, maxWidth int) fixed.Int26_6 {
    37  	mw := fixed.I(maxWidth)
    38  	if dir.Progression() == system.TowardOrigin {
    39  		switch a {
    40  		case Start:
    41  			a = End
    42  		case End:
    43  			a = Start
    44  		}
    45  	}
    46  	switch a {
    47  	case Middle:
    48  		return (mw - width) / 2
    49  	case End:
    50  		return (mw - width)
    51  	case Start:
    52  		return 0
    53  	default:
    54  		panic(fmt.Errorf("unknown alignment %v", a))
    55  	}
    56  }