News ticker with moving text from left to right

后端 未结 2 384
南方客
南方客 2020-12-20 06:59

I am trying to make a rss news ticker which will display the text,the text need move from left to right

I made the the code and text is moving from left to

2条回答
  •  失恋的感觉
    2020-12-20 07:45

    Windows Forms Marquee Label - Horizontal

    I've already posted an example of how to create a Marquee Label to animate text from top to bottom, by using a Timer and overriding OnPaint method of a custom draw control in this post: Windows Forms Top to Bottom Marquee Label.

    In the following code, I've changed that example to animates the text horizontally from right to left or left to right. It's enough to set RightToLeft property of the control to change the direction. Also don't forget to set AutoSize to false.

    Example - Right to Left and Left to Right Marquee Label in Windows Forms

    using System;
    using System.Drawing;
    using System.Windows.Forms;
    public class MarqueeLabel : Label
    {
        Timer timer;
        public MarqueeLabel()
        {
            DoubleBuffered = true;
            timer = new Timer() { Interval = 100 };
            timer.Enabled = true;
            timer.Tick += Timer_Tick;
        }
        int? left;
        int textWidth = 0;
        private void Timer_Tick(object sender, EventArgs e)
        {
            if (RightToLeft == RightToLeft.Yes)
            {
                left += 3;
                if (left > Width)
                    left = -textWidth;
            }
            else
            {
                left -= 3;
                if (left < -textWidth)
                    left = Width;
            }
            Invalidate();
        }
        protected override void OnPaint(PaintEventArgs e)
        {
            e.Graphics.Clear(BackColor);
            var s = TextRenderer.MeasureText(Text, Font, new Size(0, 0),
                TextFormatFlags.TextBoxControl | TextFormatFlags.SingleLine);
            textWidth = s.Width;
            if (!left.HasValue) left = Width;
            var format = TextFormatFlags.TextBoxControl | TextFormatFlags.SingleLine |
                TextFormatFlags.VerticalCenter;
            if (RightToLeft == RightToLeft.Yes)
            {
                format |= TextFormatFlags.RightToLeft;
                if (!left.HasValue) left = -textWidth;
            }
            TextRenderer.DrawText(e.Graphics, Text, Font,
                new Rectangle(left.Value, 0, textWidth, Height),
                ForeColor, BackColor, format);
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
                timer.Dispose();
            base.Dispose(disposing);
        }
    }
    

提交回复
热议问题