Commit 40c1fed9 authored by shrabbit's avatar shrabbit
Browse files

feat(AllColor): 新增颜色渐变输出,支持参数指定每通道颜色数及按 Q 取消

parent a2fc9e49
Loading
Loading
Loading
Loading
+51 −1
Original line number Diff line number Diff line
@@ -9,6 +9,56 @@ public class AllColor : IPlayground
    public string? Description { get; } = "相比 16 色内置控制台,Spectre 支持更多颜色。";
    public async Task Run(string[] args)
    {
        AnsiConsole.WriteLine("嘿嘿");
        var cpc = args.Length > 0 ? byte.Parse(args[0]) : 255;
        var ct = new CancellationTokenSource();

        _ = Task.Run(() =>
        {
            while (Console.ReadKey().Key == ConsoleKey.Q)
            {
                if (ct is null)
                    return;
                
                ct?.Cancel();
            }
        }, ct.Token);
        
        await MakeGradient(cpc, ct.Token);
        ct?.Cancel();
        AnsiConsole.WriteLine();
    }

    private async Task MakeGradient(int colorsPerChannel, CancellationToken ct = default)
    {
        var i = 255 / colorsPerChannel;

        try
        {
            for (float r = 0; r < 255; r += i)
            {
                ct.ThrowIfCancellationRequested();
                
                for (float g = 0; g < 255; g += i)
                {
                    ct.ThrowIfCancellationRequested();
                    
                    for (float b = 0; b < 255; b += i)
                    {
                        ct.ThrowIfCancellationRequested();
                        
                        var tr = (byte)Math.Clamp(Math.Floor(r), 0, 255);
                        var tg = (byte)Math.Clamp(Math.Floor(g), 0, 255);
                        var tb = (byte)Math.Clamp(Math.Floor(b), 0, 255);

                        var tx = new Text(" ", new Style(null, new Color(tr, tg, tb)));
                        AnsiConsole.Write(tx);
                    }
                }
            }
        }
        catch (OperationCanceledException)
        {
            
        }
    }
}
 No newline at end of file