萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

WinForms 狀態列跑馬燈文字動畫實作 (GDI+ 繪圖)

效果展示

在表單下方狀態列區域,文字從右向左連續捲動,形成跑馬燈效果。使用 `Timer` 觸發、`Graphics.MeasureString` 計算寬度、`Graphics.DrawString` 繪製。

完整程式碼 (C# WinForms)


using System;
using System.Drawing;
using System.Windows.Forms;

namespace MarqueeDemo
{
    public partial class MainForm : Form
    {
        private Label _label;          // 顯示區域
        private Timer _timer;          // 動畫計時器
        private string _text = "歡迎使用本系統 — C# WinForms 跑馬燈示範 — 當前時間: " + DateTime.Now.ToString("HH:mm:ss");
        private PointF _position;      // 文字目前繪製位置
        private Font _font = new Font("Microsoft JhengHei", 10, FontStyle.Regular);
        private Brush _brush = Brushes.Black;
        private Color _backColor = Color.White;
        private string _lastText;      // 偵測文字變更

        public MainForm()
        {
            InitializeComponent();
            InitializeMarquee();
        }

        private void InitializeComponent()
        {
            this.Text = "跑馬燈示範";
            this.Size = new Size(600, 150);
        }

        private void InitializeMarquee()
        {
            // 建立 Label 作為繪圖畫布
            _label = new Label
            {
                Location = new Point(10, 10),
                Size = new Size(this.ClientSize.Width - 20, 30),
                BorderStyle = BorderStyle.FixedSingle,
                BackColor = _backColor
            };
            this.Controls.Add(_label);

            // 計時器:每 50ms 重繪一次 (~20 FPS)
            _timer = new Timer { Interval = 50, Enabled = true };
            _timer.Tick += Timer_Tick;

            // 初始位置:從 Label 右邊界外開始
            _position = new PointF(_label.Width, 0);
            _lastText = _text;
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            // 文字內容若改變,重置位置
            if (_text != _lastText)
            {
                _position = new PointF(_label.Width, 0);
                _lastText = _text;
            }

            using (Graphics g = _label.CreateGraphics())
            {
                // 清除背景
                g.Clear(_backColor);

                // 測量文字寬度
                SizeF textSize = g.MeasureString(_text, _font);

                // 計算新位置:每幀左移 2 像素
                _position.X -= 2;

                // 文字完全移出左側 → 重置到右側
                if (_position.X < -textSize.Width)
                {
                    _position.X = _label.Width;
                }

                // 繪製文字
                g.DrawString(_text, _font, _brush, _position);
            }
        }

        // 示範:動態更新文字
        private void btnUpdateText_Click(object sender, EventArgs e)
        {
            _text = $"新訊息: {DateTime.Now:HH:mm:ss} - 這是動態更新的跑馬燈內容";
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            _timer?.Dispose();
            _font?.Dispose();
            base.OnFormClosing(e);
        }
    }
}

關鍵技術點解析

  1. CreateGraphics():取得控制項繪圖介面,**需配合 `using` 確保釋放**,避免 GDI 物件洩漏。
  2. MeasureString:精確計算文字像素寬度,決定何時重置位置。
  3. 雙重緩衝:Label 預設不支援雙重緩衝,快速移動可能閃爍。進階做法:繪製到 `Bitmap` 再 `DrawImage`,或繼承 `Control` 設定 `DoubleBuffered = true`。
  4. Timer 間隔:50ms (20 FPS) 平衡流暢度與 CPU;可依文字長度、速度調整。
  5. 字體/筆刷:建構一次重複使用,**不要在 Tick 事件中 `new Font()`/`new Brush()`**,會造成大量 GC 壓力。

進階強化版:無縫循環、暫停/繼續、滑鼠懸停停止


public class MarqueeLabel : Control
{
    private readonly Timer _timer = new Timer { Interval = 30 };
    private string _text = "";
    private float _x;
    private readonly Font _font = new Font("Microsoft JhengHei", 10);
    private readonly StringFormat _sf = new StringFormat { FormatFlags = StringFormatFlags.NoWrap };

    public string MarqueeText
    {
        get => _text;
        set { _text = value ?? ""; ResetPosition(); Invalidate(); }
    }

    public MarqueeLabel()
    {
        SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);
        _timer.Tick += (s, e) => { _x -= 1.5f; if (_x < -TextWidth) _x = Width; Invalidate(); };
        _timer.Start();
        this.MouseEnter += (s, e) => _timer.Stop();
        this.MouseLeave += (s, e) => _timer.Start();
    }

    private float TextWidth => CreateGraphics().MeasureString(_text, _font).Width;

    private void ResetPosition() => _x = Width;

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        if (string.IsNullOrEmpty(_text)) return;
        // 繪製兩份文字實現無縫循環
        e.Graphics.DrawString(_text, _font, Brushes.Black, _x, 0, _sf);
        if (_x + TextWidth < Width) // 第二份銜接
            e.Graphics.DrawString(_text, _font, Brushes.Black, _x + TextWidth, 0, _sf);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing) { _timer.Dispose(); _font.Dispose(); }
        base.Dispose(disposing);
    }
}

現代替代方案

  • WPF:`...` 純 XAML 動畫,GPU 加速、無閃爍。
  • Web (Blazor/ASP.NET Core):CSS `animation: marquee 10s linear infinite;` `@keyframes marquee { from { transform: translateX(100%); } to { transform: translateX(-100%); } }`
  • 第三方控制項:DevExpress, Telerik, Syncfusion 內建 Marquee/Scrolling Label。

WinForms GDI+ 手繪跑馬燈適合簡單工具、學習繪圖機制;正式產品建議使用雙重緩衝自訂控制項或遷移至 WPF/Web 技術棧獲得更佳視覺品質與維護性。

copyright © 萬盛學電腦網 all rights reserved