我会给你一个昂贵的代码,给那些不想花 9 块钱下载一个特殊库的人。
static void Progressbar() {
var blackBlock = "█";
var middleBlock = "▓";
var ligthBlock = "▒";
int blockCount = 100;
int start = 11;
Console.ForegroundColor = ConsoleColor.Cyan;
var posY = Console.CursorTop;
//var LOADING = " Loading: [{0}{1}{2}]";
// Console.Write(LOADING);
Console.BackgroundColor = ConsoleColor.Blue;
string TEMPLATE = " Loading: [{0}{1}{2}] ";
Console.SetCursorPosition(start, posY);
for (int i = 0; i < 50; i++) {
/* Thread.Sleep(100);
TimeSpan.FromSeconds(100);
Console.Write("{0}", new string(' ', ligthBlock.Length));
Console.SetCursorPosition(Console.CursorLeft - 1, posY);
Console.Write("{0}", new string(' ', middleBlock.Length));
Thread.Sleep(100);
Console.BackgroundColor = ConsoleColor.DarkBlue;
Console.SetCursorPosition(Console.CursorLeft - 1, posY);
Console.Write("{0}", new string(' ', blackBlock.Length));
*/
Thread.Sleep(200);
TimeSpan.FromSeconds(200);
Console.BackgroundColor = ConsoleColor.Gray;
var output = string.Format(" Loading: [{0}{1}{2}] ",
new string(' ', ligthBlock.Length),
new string(' ', middleBlock.Length),
new string(' ', blackBlock.Length));
Console.Write(output);
}
Console.BackgroundColor = ConsoleColor.White;
Console.Write("] \n");
}
升级版:
static void Progressbar() {
int blockCount = 100;
int start = 11;
var posY = Console.CursorTop;
// //012345678911
string template = " Loading: [{0}{1}{2} ] {3}% {4}s";
Console.WriteLine(template);
int maxProgress = 50;
ConsoleProgressBar bar = new ConsoleProgressBar(11, posY, maxProgress);
long previous = -1;
long total = 1000000000;
for (long i = 0; i < total; i++) {
long progress = i * maxProgress / total;
if (progress != previous) {
bar.ShowProgress((int)progress);
previous = progress;
}
}
bar.ShowProgress(maxProgress);
Console.BackgroundColor = ConsoleColor.White;
}
}
public class ConsoleProgressBar {
public int Left { get; set; }
public int Top { get; set; }
public int Length { get; set; }
public ConsoleProgressBar(int left, int top, int length) {
Left = left;
Top = top;
Length = length;
}
public void ShowProgress(int progress) {
if (progress > Length || progress < 0)
throw new ArgumentException($"Invalid progress value, must be between 0 and {Length} but actual {progress}.");
int start = 0;
(int left, int top) = Console.GetCursorPosition();
Console.SetCursorPosition(Left, Top);
Thread.Sleep(100);
Console.Write($"{new string('█', progress)}" +
$"{new string('▓', progress)}" +
$"{new string('░', Length - progress)}" +
$"{new string(Convert.ToChar(start++), Length - progress)}" +
$"{new string(Convert.ToChar(Timer.ActiveCount), Length - progress)}");
Console.SetCursorPosition(left, top);
Thread.Sleep(100);
}
}
为什么不显示]
,完成百分比,完成时间?并且要注意进度条的一半█
还没有结束。在加载过程中括号之间,如果需要,您还可以腾出空闲空间,即ShowProgress
指定第二个参数将检查括号之间的空白是否必要并被填充。
我究竟做错了什么?