Winform开发:在ProgressBar显示百分比数字

如果不使用Label而是直接在进度条上显示文字,可以扩展一个派生类自己画,代码如下:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            var progressBar = new MyProgressBar()
                {
                    Location = new Point(20, Bottom - 150),
                    Size = new Size(Width - 60, 50),
                    Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom
                };
            this.Controls.Add(progressBar);

            var timer = new Timer {Interval = 150};
            timer.Tick += (s, e) => progressBar.Value = progressBar.Value%100 + 1;
            timer.Start();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }
    }

    public class MyProgressBar : ProgressBar
    {
        public MyProgressBar()
        {
            SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            Rectangle rect = ClientRectangle;
            Graphics g = e.Graphics;

            ProgressBarRenderer.DrawHorizontalBar(g, rect);
            rect.Inflate(-3, -3);
            if (Value > 0)
            {
                var clip = new Rectangle(rect.X, rect.Y, (int) ((float) Value/Maximum*rect.Width), rect.Height);
                ProgressBarRenderer.DrawHorizontalChunks(g, clip);
            }

            string text = string.Format("{0}%", Value * 100 / Maximum);;
            using (var font = new Font(FontFamily.GenericSerif, 20))
            {
                SizeF sz = g.MeasureString(text, font);
                var location = new PointF(rect.Width/2 - sz.Width/2, rect.Height/2 - sz.Height/2 + 2);
                g.DrawString(text, font, Brushes.Red, location);
            }
        }
    }

 

posted @ 2016-09-22 16:17  Nullobj  阅读(8359)  评论(0编辑  收藏  举报