Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add converter from image/color.Color to tcell.Color #456

Merged
merged 1 commit into from May 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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)
}
}