Add info on measuring width/height to README + add Size helper function

This commit is contained in:
Christian Rocha 2021-04-28 15:58:18 -04:00
parent 1e530f78cb
commit 493d49e38a
2 changed files with 32 additions and 3 deletions

View File

@ -261,9 +261,29 @@ lipgloss.HorizontalJoin(0.2, paragraphA, paragraphB, paragraphC)
```
### Measuring Width and Height
Sometimes youll want to know the width and height of text blocks when building
your layouts:
```go
var block string = lipgloss.NewStyle().
Width(40).
Padding(2).
Render(someLongString)
// Get the actual, phsical dimensions of the text block.
width := lipgloss.Width(block)
height := lipgloss.Height(block)
// Here's a shorthand function.
w, h := lipgloss.Size(block)
```
### Placing Text in Whitespace
Sometimes you simply want to place a block of text in whitespace.
Sometimes youll simply want to place a block of text in whitespace.
```go
// Center a paragraph horizontally in a space 80 cells wide. The height of

13
size.go
View File

@ -7,8 +7,8 @@ import (
)
// Width returns the cell width of characters in the string. ANSI sequences are
// ignored and characters wider than one cell (such as Chinese characters) are
// appropriately measured.
// ignored and characters wider than one cell (such as Chinese characters and
// emojis) are appropriately measured.
//
// You should use this instead of len(string) len([]rune(string) as neither
// will give you accurate results.
@ -30,3 +30,12 @@ func Width(str string) (width int) {
func Height(str string) int {
return strings.Count(str, "\n") + 1
}
// Size returns the width and height of the string in cells. ANSI sequences are
// ignored and characters wider than one cell (such as Chinese characters and
// emojis) are appropriately measured.
func Size(str string) (width, height int) {
width = Width(str)
height = Height(str)
return width, height
}