...

Source file src/github.com/gdamore/tcell/v2/colorfit.go

Documentation: github.com/gdamore/tcell/v2

     1  // Copyright 2016 The TCell Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use file except in compliance with the License.
     5  // You may obtain a copy of the license at
     6  //
     7  //    http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package tcell
    16  
    17  import (
    18  	"math"
    19  
    20  	"github.com/lucasb-eyer/go-colorful"
    21  )
    22  
    23  // FindColor attempts to find a given color, or the best match possible for it,
    24  // from the palette given.  This is an expensive operation, so results should
    25  // be cached by the caller.
    26  func FindColor(c Color, palette []Color) Color {
    27  	match := ColorDefault
    28  	dist := float64(0)
    29  	r, g, b := c.RGB()
    30  	c1 := colorful.Color{
    31  		R: float64(r) / 255.0,
    32  		G: float64(g) / 255.0,
    33  		B: float64(b) / 255.0,
    34  	}
    35  	for _, d := range palette {
    36  		r, g, b = d.RGB()
    37  		c2 := colorful.Color{
    38  			R: float64(r) / 255.0,
    39  			G: float64(g) / 255.0,
    40  			B: float64(b) / 255.0,
    41  		}
    42  		// CIE94 is more accurate, but really really expensive.
    43  		nd := c1.DistanceCIE76(c2)
    44  		if math.IsNaN(nd) {
    45  			nd = math.Inf(1)
    46  		}
    47  		if match == ColorDefault || nd < dist {
    48  			match = d
    49  			dist = nd
    50  		}
    51  	}
    52  	return match
    53  }
    54  

View as plain text