Implemented all text alignment methods

This commit is contained in:
Sasha Koshka 2023-03-16 20:24:33 -04:00
parent 6258c77f86
commit cdf805dadc
2 changed files with 54 additions and 7 deletions

View File

@ -98,10 +98,11 @@ func (word WordLayout) FirstRune () rune {
// LineLayout contains layout information for a single line. // LineLayout contains layout information for a single line.
type LineLayout struct { type LineLayout struct {
Y fixed.Int26_6 Y fixed.Int26_6
Width fixed.Int26_6 Width fixed.Int26_6
SpaceAfter fixed.Int26_6 ContentWidth fixed.Int26_6
Words []WordLayout SpaceAfter fixed.Int26_6
Words []WordLayout
BreakAfter bool BreakAfter bool
} }
@ -147,12 +148,15 @@ func DoLine (text []rune, face font.Face, maxWidth fixed.Int26_6) (line LineLayo
isFirstWord = false isFirstWord = false
} }
// set the width of the line's content.
line.ContentWidth = lastWord.X + lastWord.Width
// set the line's width. this is subject to be overridden by the // set the line's width. this is subject to be overridden by the
// TypeSetter to match the longest line. // TypeSetter to match the longest line.
if maxWidth > 0 { if maxWidth > 0 {
line.Width = maxWidth line.Width = maxWidth
} else { } else {
line.Width = lastWord.X + lastWord.Width line.Width = line.ContentWidth
line.SpaceAfter = lastWord.SpaceAfter line.SpaceAfter = lastWord.SpaceAfter
} }
return return
@ -161,5 +165,44 @@ func DoLine (text []rune, face font.Face, maxWidth fixed.Int26_6) (line LineLayo
// Align aligns the text in the line according to the specified alignment // Align aligns the text in the line according to the specified alignment
// method. // method.
func (line *LineLayout) Align (align Align) { func (line *LineLayout) Align (align Align) {
// TODO if len(line.Words) == 0 { return }
if align == AlignJustify {
line.justify()
return
}
leftOffset := -line.Words[0].X
if align == AlignCenter {
leftOffset += (line.Width - line.ContentWidth) / 2
} else if align == AlignRight {
leftOffset += line.Width - line.ContentWidth
}
for index := range line.Words {
line.Words[index].X += leftOffset
}
}
func (line *LineLayout) justify () {
if len(line.Words) < 2 {
line.Align(AlignLeft)
return
}
// We are going to be moving the words, so we can't take SpaceAfter into
// account.
trueContentWidth := fixed.Int26_6(0)
for _, word := range line.Words {
trueContentWidth += word.Width
}
spaceCount := fixed.Int26_6(len(line.Words) - 1)
spacePerWord := (line.Width - trueContentWidth) / spaceCount
x := fixed.Int26_6(0)
for index, word := range line.Words {
line.Words[index].X = x
x += spacePerWord + word.Width
}
} }

View File

@ -95,7 +95,11 @@ func (setter *TypeSetter) needAlignedLayout () {
setter.alignClean = true setter.alignClean = true
for index := range setter.lines { for index := range setter.lines {
setter.lines[index].Align(setter.align) align := setter.align
if index == len(setter.lines) - 1 && align == AlignJustify {
align = AlignLeft
}
setter.lines[index].Align(align)
} }
} }