gerson
2024-12-29 4565042a171a1828fbf23fac78bf7b24fb293ffd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import type { NumberRange, ValueRange } from './basic';
export type Rgb = [number, number, number];
 
export type ColorRange = ValueRange<Rgb>;
export class ColorMapper {
    private readonly _colorRange = null;
    private readonly _valueRange = null;
 
    constructor(valueRange: NumberRange, colorRange: ColorRange) {
        this._colorRange = colorRange;
        this._valueRange = valueRange;
    }
 
    private mapValueToColor(value): Rgb {
        const { min: valueMin, max: valueMax } = this.valueRange;
        const { min: colorMin, max: colorMax } = this.colorRange;
 
        // 确保值在范围内
        const clampedValue = Math.min(Math.max(value, valueMin), valueMax);
 
        // 计算归一化值(0到1之间的值)
        const normalizedValue = (clampedValue - valueMin) / (valueMax - valueMin);
 
        // 使用线性插值计算颜色分量
        const red = Math.floor(colorMin[0] + (colorMax[0] - colorMin[0]) * normalizedValue);
        const green = Math.floor(colorMin[1] + (colorMax[1] - colorMin[1]) * normalizedValue);
        const blue = Math.floor(colorMin[2] + (colorMax[2] - colorMin[2]) * normalizedValue);
 
        // 返回 RGB 颜色字符串
        // return `rgb(${red}, ${green}, ${blue})`;
        return [red, green, blue];
    }
 
    /**
     * 通过值获取颜色
     * @param value
     */
    getByValue(value: number) {
        const rgb = this.mapValueToColor(value);
        return rgb;
    
    }
 
    public get colorRange(): ColorRange {
        return this._colorRange;
    }
 
    public get valueRange(): NumberRange {
        return this._valueRange;
    }
}