How can I cycle through hex color codes in PHP?

前端 未结 9 2143
野的像风
野的像风 2021-01-06 06:08

I want an array where each field in the array contains a color code

array(0 => \'#4CFF00\', 1 => \'#FFE97F\')

And I want this to go t

9条回答
  •  离开以前
    2021-01-06 06:39

    function list_colours($start, $end, $steps = 6)
    {
        $return = array();
    
        $start_r = hexdec(substr($start, 1, 2));
        $start_g = hexdec(substr($start, 3, 2));
        $start_b = hexdec(substr($start, 5, 2));
    
        $end_r = hexdec(substr($end, 1, 2));
        $end_g = hexdec(substr($end, 3, 2));
        $end_b = hexdec(substr($end, 5, 2));
    
        $shift_r = ($end_r - $start_r) / $steps;
        $shift_g = ($end_g - $start_g) / $steps;
        $shift_b = ($end_b - $start_b) / $steps;
    
        for ($i = 0; $i < $steps; $i++)
        {
            $color = array();
            $color[] = dechex($start_r + ($i * $shift_r));
            $color[] = dechex($start_g + ($i * $shift_g));
            $color[] = dechex($start_b + ($i * $shift_b));
    
            // Pad with zeros.
            $color = array_map(function ($item) {
                    return str_pad($item, 2, "0", STR_PAD_LEFT);
                },
                $color
            );
    
            $return[] = '#' . implode($color);
        }
    
        return $return;
    }
    
    // Examples
    $spectrum = array();
    $spectrum[] = list_colours("#000000", "#FFFFFF"); // grey
    $spectrum[] = list_colours("#cc0033", "#FFFFFF"); // R
    $spectrum[] = list_colours("#ff6600", "#FFFFFF"); // O
    $spectrum[] = list_colours("#fdc710", "#FFFFFF"); // Y
    $spectrum[] = list_colours("#cccc00", "#FFFFFF"); // G
    $spectrum[] = list_colours("#339933", "#FFFFFF"); // G dark
    $spectrum[] = list_colours("#339999", "#FFFFFF"); // B teal
    $spectrum[] = list_colours("#14acde", "#FFFFFF"); // B light
    $spectrum[] = list_colours("#0066cc", "#FFFFFF"); // B dark
    $spectrum[] = list_colours("#663399", "#FFFFFF"); // I dark
    $spectrum[] = list_colours("#990066", "#FFFFFF"); // I light
    $spectrum[] = list_colours("#cc0066", "#FFFFFF"); // V pink
    

提交回复
热议问题