Debian Codegraph @

exp/color/blend.go

raw ◀ ▶
1 Debian patch touch this file
•1 // Package color contains utilities for working with colors.
2 package color
3
4 import (
5 "image/color"
6
7 "github.com/lucasb-eyer/go-colorful"
8 )
9
10 // Blend returns a slice of colors blended between the given
11 // colors. Blending is done as Hcl to stay in gamut.
12 //
13 // Example:
14 //
15 // red := color.RGBA{R: 0xff, G: 0x00, B: 0x00, A: 0xff}
16 // blue := color.RGBA{R: 0x00, G: 0x00, B: 0xff, A: 0xff}
17 //
18 // blend := Blend(10, red, blue)
19 // var b strings.Builder
20 //
21 // for _, c := range blend {
22 // b.WriteString(lipgloss.NewStyle().Background(c).Render(" "))
23 // }
24 //
25 // lipgloss.Println(b.String())
26 func Blend(size int, points ...color.Color) []color.Color {
27 if size <= 0 || len(points) < 2 {
28 return nil
29 }
30 if size == 1 {
31 return []color.Color{points[0]}
32 }
33
34 stops := make([]colorful.Color, len(points))
35 for i, c := range points {
36 stops[i], _ = colorful.MakeColor(c)
37 }
38
39 numSegments := len(stops) - 1
40 blended := make([]color.Color, 0, size)
41
42 // Calculate how many colors each segment should have.
43 segmentSizes := make([]int, numSegments)
44 baseSize := size / numSegments
45 remainder := size % numSegments
46
47 // Distribute the remainder across segments.
48 for i := range numSegments {
49 segmentSizes[i] = baseSize
50 if i < remainder {
51 segmentSizes[i]++
52 }
53 }
54
55 // Generate colors for each segment.
56 for i := range numSegments {
57 c1 := stops[i]
58 c2 := stops[i+1]
59 segmentSize := segmentSizes[i]
60
61 for j := range segmentSize {
62 t := float64(j) / float64(segmentSize)
63 c := c1.BlendHcl(c2, t)
64 blended = append(blended, c)
65 }
66 }
67
68 return blended
69 }