因为群里的一个朋友在问跑马灯的弄法,看到了很多人仅仅只是用移动label的坐标的这种不太实用的方式,于是专门写了个跑马灯效果的Label,暂时只写了跑马灯文字走向4个方向。
public class MarqueeLabel : Label
{
private float CurrentPosition { get; set; }
private Timer Timer;
private MarqueeDirection md = MarqueeDirection.LeftToRight;
public MarqueeDirection MarqueeDirection
{
get { return md; }
set {
md = value;
if (md == MarqueeDirection.LeftToRight)
{
CurrentPosition = 0;
}
else if (md == MarqueeDirection.RightToLeft)
{
CurrentPosition = Width;
}
else if (md == MarqueeDirection.TopToBottom)
{
CurrentPosition = 0;
}
else
{
CurrentPosition = Height;
}
}
}
public MarqueeLabel()
{
UseCompatibleTextRendering = true;
Timer = new Timer();
Timer.Interval = 50;
Timer.Tick += Timer_Tick;
Timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
Graphics gh = this.CreateGraphics();
SizeF sf = gh.MeasureString(this.Text, this.Font);
if (md == MarqueeDirection.LeftToRight)
{
if (CurrentPosition > Width)
CurrentPosition = -sf.Width;
else
CurrentPosition += 2;
}
else if (md == MarqueeDirection.RightToLeft)
{
if (CurrentPosition > -sf.Width)
CurrentPosition -= 2;
else
CurrentPosition = Width;
}
else if (md == MarqueeDirection.TopToBottom)
{
if (CurrentPosition > Height)
CurrentPosition = -sf.Height;
else
CurrentPosition += 2;
}
else
{
if (CurrentPosition > -sf.Height)
CurrentPosition -= 2;
else
CurrentPosition = Height;
}
Invalidate();
}
protected override void OnPaint(PaintEventArgs e)
{
if (md == MarqueeDirection.LeftToRight || md == MarqueeDirection.RightToLeft)
{
e.Graphics.TranslateTransform((float)CurrentPosition, 0);
}
else
{
e.Graphics.TranslateTransform(0, (float)CurrentPosition);
}
base.OnPaint(e);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (Timer != null)
Timer.Dispose();
}
Timer = null;
}
}
public enum MarqueeDirection : int
{
LeftToRight = 0,
RightToLeft = 1,
TopToBottom = 2,
BottomToTop = 3
}
运行基本OK,可能存在一点小瑕疵,若文字太多而Label高度太小会导致显示不全。