Skip to content

Commit

Permalink
Implement FromImageColor
Browse files Browse the repository at this point in the history
Converts from `image/color.Color` to `tcell.Color`.
  • Loading branch information
spenserblack authored and gdamore committed May 11, 2021
1 parent 299cb41 commit 8f925d8
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
16 changes: 14 additions & 2 deletions color.go
Expand Up @@ -14,7 +14,10 @@

package tcell

import "strconv"
import (
ic "image/color"
"strconv"
)

// Color represents a color. The low numeric values are the same as used
// by ECMA-48, and beyond that XTerm. A 24-bit RGB value may be used by
Expand Down Expand Up @@ -1066,4 +1069,13 @@ func GetColor(name string) Color {
// PaletteColor creates a color based on the palette index.
func PaletteColor(index int) Color {
return Color(index) | ColorValid
}
}

// FromImageColor converts an image/color.Color into tcell.Color.
// The alpha value is dropped, so it should be tracked separately if it is
// needed.
func FromImageColor(imageColor ic.Color) Color {
r, g, b, _ := imageColor.RGBA()
// NOTE image/color.Color RGB values range is [0, 0xFFFF] as uint32
return NewRGBColor(int32(r>>8), int32(g>>8), int32(b>>8))
}
17 changes: 17 additions & 0 deletions color_test.go
Expand Up @@ -15,6 +15,7 @@
package tcell

import (
ic "image/color"
"testing"
)

Expand Down Expand Up @@ -110,3 +111,19 @@ func TestColorRGB(t *testing.T) {
t.Errorf("RGB wrong (%x, %x, %x)", r, g, b)
}
}

func TestFromImageColor(t *testing.T) {
red := ic.RGBA{0xFF, 0x00, 0x00, 0x00}
white := ic.Gray{0xFF}
cyan := ic.CMYK{0xFF, 0x00, 0x00, 0x00}

if hex := FromImageColor(red).Hex(); hex != 0xFF0000 {
t.Errorf("%v is not 0xFF0000", hex)
}
if hex := FromImageColor(white).Hex(); hex != 0xFFFFFF {
t.Errorf("%v is not 0xFFFFFF", hex)
}
if hex := FromImageColor(cyan).Hex(); hex != 0x00FFFF {
t.Errorf("%v is not 0x00FFFF", hex)
}
}

0 comments on commit 8f925d8

Please sign in to comment.