在控制檯中繪製圖像是一件很是有趣的事,不知情的人看到了會感受很驚訝,若是你有GDI+繪製基礎,那麼繼續往下看。函數
Imports System.Drawing Imports System.Runtime.InteropServices Module Module1 '引用WIN32API,該函數用來獲取當前命令行的窗口句柄,以便後面從該句柄建立畫布 <DllImport("kernel32.dll", SetLastError:=True)> Private Function GetConsoleWindow() As IntPtr End Function Dim H As IntPtr = GetConsoleWindow() Sub Main() '隨便輸出一行文本 Console.Title = "腳本編譯器" Console.ReadKey() Dim S As String = "正在將腳本編譯爲可執行Exe文件..." Console.Write(S) Console.ForegroundColor = ConsoleColor.White For I As Integer = 1 To 100 Step 2 '依次從1到100繪製一個進度條 DrawPersion(I) Threading.Thread.Sleep(100) Next '最後再繪製一次100%時的進度條 DrawPersion(100) Console.WriteLine() Console.WriteLine() Console.WriteLine() Console.WriteLine("操做完成") While True Console.ReadKey() Console.WriteLine() End While End Sub '繪製進度條過程 Private Sub DrawPersion(I As Integer) Dim T As Integer = Console.CursorTop Dim S As String = "正在將腳本編譯爲可執行Exe文件..." Using G As Graphics = Graphics.FromHwnd(H) G.SmoothingMode = Drawing2D.SmoothingMode.HighQuality '設置光標位置,計算出位置應該在文本結尾 Console.SetCursorPosition(S.Length * 2, T) '經過當前命令行文本行數計算出最末行的起始位置,用以繪製圖像 Dim N As Integer = (T + 1) * Console.CursorSize - 5 '繪製一個圖片上去 G.DrawImage(My.Resources.Compile, New Rectangle(0, N, 16, 16), New Rectangle(0, 0, 16, 16), GraphicsUnit.Pixel) '因爲圖片大小已知,又可計算出進度條左上角的起始位置,如下爲繪製一個線性漸變的進度條 Using Lg As New Drawing2D.LinearGradientBrush(New Point(0, N), New Point(0, N + Console.CursorSize), Color.SteelBlue, Color.DodgerBlue) '模擬值範圍爲0到300,並乘以當前傳入的循環I值 Dim L As Integer = 300 / 100 * I '用線性漸變填充一個矩形,該矩形是上面計算出的從圖片右側和同行Y值,長度爲當前I比例的矩形 G.FillRectangle(Lg, New Rectangle(20, N, L, 16)) '獲得進度文本的左上角,其實就是進度條矩形的左上角 Dim Pt As Point = New Point(20, N) '繪製黑色文本模擬投影 G.DrawString(String.Format("{0}%", I), New Font("宋體", 12, FontStyle.Bold), Brushes.Black, Pt) '座標往左上角偏移1像素繪製白色文本 Pt += New Point(-1, -1) G.DrawString(String.Format("{0}%", I), New Font("宋體", 12, FontStyle.Bold), Brushes.White, Pt) End Using End Using End Sub End Module
運行效果命令行
代碼中用到的素材圖片orm