diff --git a/color.go b/color.go index 8a13a073..97c0c2a2 100644 --- a/color.go +++ b/color.go @@ -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 @@ -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 -} \ No newline at end of file +} + +// 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)) +} diff --git a/color_test.go b/color_test.go index a724f1f3..d0e1ce0a 100644 --- a/color_test.go +++ b/color_test.go @@ -15,6 +15,7 @@ package tcell import ( + ic "image/color" "testing" ) @@ -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) + } +}