Skip to content

Commit

Permalink
Add info on measuring width/height to README + add Size helper function
Browse files Browse the repository at this point in the history
  • Loading branch information
meowgorithm committed Apr 29, 2021
1 parent 1e530f7 commit 493d49e
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
22 changes: 21 additions & 1 deletion README.md
Expand Up @@ -261,9 +261,29 @@ lipgloss.HorizontalJoin(0.2, paragraphA, paragraphB, paragraphC)
```


### Measuring Width and Height

Sometimes you’ll 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 you’ll simply want to place a block of text in whitespace.

```go
// Center a paragraph horizontally in a space 80 cells wide. The height of
Expand Down
13 changes: 11 additions & 2 deletions size.go
Expand Up @@ -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.
Expand All @@ -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
}

0 comments on commit 493d49e

Please sign in to comment.