C# 文字滚动特效(上下滚动)
本程序改编至网上下载的一个自定义控件,原控件是左右滚动效果,类似于跑马灯效果,由于项目需要,改编为上下滚动。
前期没有实现自动折行,今天刚加上自动折行。
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Data;
using System.Windows.Forms;
using System.Collections.Generic; namespace OI.Common.Controls
{
/* 【原功能为文字左右滚动控件】
* 此控件修改滚动方式为由下至上
* 修改人:王志超
* 时间:2014-02-10
* 修改内容:public void DrawScrollingText(Graphics canvas)
*/ /// <summary>
/// Summary description for ScrollingTextControl.
/// </summary>
[
ToolboxBitmapAttribute(typeof(OI.Common.Controls.ScrollingText), "ScrollingText.bmp"),
DefaultEvent("TextClicked")
]
public class ScrollingText : System.Windows.Forms.Control
{
private Timer timer; // Timer for text animation.
private string text = "Text"; // Scrolling text
private float staticTextPos = ; // The running x pos of the text
private float yPos = ; // The running y pos of the text
private ScrollDirection scrollDirection = ScrollDirection.RightToLeft; // The direction the text will scroll
private ScrollDirection currentDirection = ScrollDirection.LeftToRight; // Used for text bouncing
private VerticleTextPosition verticleTextPosition = VerticleTextPosition.Center; // Where will the text be vertically placed
private int scrollPixelDistance = ; // How far the text scrolls per timer event
private bool showBorder = true; // Show a border or not
private bool stopScrollOnMouseOver = false; // Flag to stop the scroll if the user mouses over the text
private bool scrollOn = true; // Internal flag to stop / start the scrolling of the text
private Brush foregroundBrush = null; // Allow the user to set a custom Brush to the text Font
private Brush backgroundBrush = null; // Allow the user to set a custom Brush to the background
private Color borderColor = Color.Black; // Allow the user to set the color of the control border
private RectangleF lastKnownRect; // The last known position of the text public ScrollingText()
{
// Setup default properties for ScrollingText control
InitializeComponent(); //This turns off internal double buffering of all custom GDI+ drawing Version v = System.Environment.Version; if (v.Major < )
{
this.SetStyle(ControlStyles.DoubleBuffer, true);
}
else
{
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
} this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.ResizeRedraw, true); //setup the timer object
timer = new Timer();
timer.Interval = ; //default timer interval
timer.Enabled = true;
timer.Tick += new EventHandler(Tick);
} /**/
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
//Make sure our brushes are cleaned up
if (foregroundBrush != null)
foregroundBrush.Dispose(); //Make sure our brushes are cleaned up
if (backgroundBrush != null)
backgroundBrush.Dispose(); //Make sure our timer is cleaned up
if (timer != null)
timer.Dispose();
}
base.Dispose(disposing);
} #region Component Designer generated code
/**/
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
//ScrollingText
this.Name = "ScrollingText";
this.Size = new System.Drawing.Size(, );
this.Click += new System.EventHandler(this.ScrollingText_Click);
}
#endregion //Controls the animation of the text.
private void Tick(object sender, EventArgs e)
{
//2014-05-10 王志超修改
RectangleF refreshRect = new RectangleF(, , this.Size.Width, this.Size.Height);
Region updateRegion = new Region(refreshRect); Invalidate(updateRegion);
Update(); //原代码如下: ////update rectangle to include where to paint for new position
////lastKnownRect.X -= 10;
////lastKnownRect.Width += 20;
//lastKnownRect.Inflate(10, 5);
////get the display rectangle
//RectangleF refreshRect = lastKnownRect;
//refreshRect.X = Math.Max(0, lastKnownRect.X);
//refreshRect.Width = Math.Min(lastKnownRect.Width + lastKnownRect.X, this.Width);
//refreshRect.Width = Math.Min(this.Width - lastKnownRect.X, refreshRect.Width);
////create region based on updated rectangle
////Region updateRegion = new Region(lastKnownRect);
//Region updateRegion = new Region(refreshRect);
////repaint the control
//Invalidate(updateRegion);
//Update();
} //Paint the ScrollingTextCtrl.
protected override void OnPaint(PaintEventArgs pe)
{
//Console.WriteLine(pe.ClipRectangle.X + ", " + pe.ClipRectangle.Y + ", " + pe.ClipRectangle.Width + ", " + pe.ClipRectangle.Height);
//Paint the text to its new position
DrawScrollingText(pe.Graphics);
//pass on the graphics obj to the base Control class
base.OnPaint(pe);
} protected override void OnSizeChanged(EventArgs e)
{
p = new PointF(, this.ClientSize.Height);
base.OnSizeChanged(e);
} PointF p;
//Draw the scrolling text on the control
public void DrawScrollingText(Graphics canvas)
{
canvas.SmoothingMode = SmoothingMode.HighQuality;
canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
//measure the size of the string for placement calculation
SizeF stringSize = canvas.MeasureString(this.text, this.Font);
//Calculate the begining x position of where to paint the text
if (scrollOn)
{
//CalcTextPosition(stringSize);
}
//Clear the control with user set BackColor
if (backgroundBrush != null)
{
canvas.FillRectangle(backgroundBrush, , , this.ClientSize.Width, this.ClientSize.Height);
}
else
{
canvas.Clear(this.BackColor);
} // Draw the border
if (showBorder)
{
using (Pen borderPen = new Pen(borderColor))
canvas.DrawRectangle(borderPen, , , this.ClientSize.Width - , this.ClientSize.Height - );
} //新增:绘制背景图片
if (this.BackgroundImage != null)
{
canvas.DrawImage(this.BackgroundImage, this.ClientRectangle);
} //修改滚动方式为由下至上。
//修改人:王志超
//时间:2014-05-10
p = new PointF(, p.Y - scrollPixelDistance);//设置偏移 List<string> textRows = GetStringRows(canvas, this.Font, this.text, this.Size.Width);
string strDraw = "";
//自动折行处理
foreach (string str in textRows)
{
strDraw += str + "\n";
}
stringSize = canvas.MeasureString(strDraw, this.Font); if (p.Y <= - * stringSize.Height)
p = new PointF(, this.ClientSize.Height);//重新开始 if (foregroundBrush == null)
{
using (Brush tempForeBrush = new System.Drawing.SolidBrush(this.ForeColor))
{
canvas.DrawString(strDraw, this.Font, tempForeBrush, p);
}
}
else
{
canvas.DrawString(strDraw, this.Font, foregroundBrush, p);
} /*以下内容为原绘制方式*/ //// Draw the text string in the bitmap in memory
//if (foregroundBrush == null)
//{
// using (Brush tempForeBrush = new System.Drawing.SolidBrush(this.ForeColor))
// canvas.DrawString(this.text, new Font("宋体", 20), tempForeBrush, 0, staticTextPos);
//}
//else
//{
// canvas.DrawString(this.text, new Font("宋体", 20), foregroundBrush, 0, staticTextPos);
//} //lastKnownRect = new RectangleF(staticTextPos, yPos, stringSize.Width, stringSize.Height);
//EnableTextLink(lastKnownRect);
} /// <summary>
/// 绘制文本自动换行(超出截断)
/// </summary>
/// <param name="graphic">绘图图面</param>
/// <param name="font">字体</param>
/// <param name="text">文本</param>
/// <param name="recangle">绘制范围</param>
private void DrawStringWrap(Graphics graphic, Font font, string text, Rectangle recangle)
{
List<string> textRows = GetStringRows(graphic, font, text, recangle.Width);
int rowHeight = (int)(Math.Ceiling(graphic.MeasureString("测试", font).Height));
int maxRowCount = recangle.Height / rowHeight;
int drawRowCount = (maxRowCount < textRows.Count) ? maxRowCount : textRows.Count;
int top = (recangle.Height - rowHeight * drawRowCount) / ;
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Near;
sf.LineAlignment = StringAlignment.Center;
for (int i = ; i < drawRowCount; i++)
{
Rectangle fontRectanle = new Rectangle(recangle.Left, top + rowHeight * i, recangle.Width, rowHeight);
graphic.DrawString(textRows[i], font, new SolidBrush(Color.Black), fontRectanle, sf);
}
} /// <summary>
/// 将文本分行
/// </summary>
/// <param name="graphic">绘图图面</param>
/// <param name="font">字体</param>
/// <param name="text">文本</param>
/// <param name="width">行宽</param>
/// <returns></returns>
private List<string> GetStringRows(Graphics graphic, Font font, string text, int width)
{
int RowBeginIndex = ;
int rowEndIndex = ;
int textLength = text.Length;
List<string> textRows = new List<string>(); for (int index = ; index < textLength; index++)
{
rowEndIndex = index;
if (index == textLength - )
{
textRows.Add(text.Substring(RowBeginIndex));
}
else if (rowEndIndex + < text.Length && text.Substring(rowEndIndex, ) == "\r\n")
{
textRows.Add(text.Substring(RowBeginIndex, rowEndIndex - RowBeginIndex));
rowEndIndex = index += ;
RowBeginIndex = rowEndIndex;
}
else if (graphic.MeasureString(text.Substring(RowBeginIndex, rowEndIndex - RowBeginIndex + ), font).Width > width)
{
textRows.Add(text.Substring(RowBeginIndex, rowEndIndex - RowBeginIndex));
RowBeginIndex = rowEndIndex;
}
} return textRows;
} private void CalcTextPosition(SizeF stringSize)
{
switch (scrollDirection)
{
case ScrollDirection.RightToLeft:
if (staticTextPos < (- * (stringSize.Width)))
staticTextPos = this.ClientSize.Width - ;
else
staticTextPos -= scrollPixelDistance;
break;
case ScrollDirection.LeftToRight:
if (staticTextPos > this.ClientSize.Width)
staticTextPos = - * stringSize.Width;
else
staticTextPos += scrollPixelDistance;
break;
case ScrollDirection.Bouncing:
if (currentDirection == ScrollDirection.RightToLeft)
{
if (staticTextPos < )
currentDirection = ScrollDirection.LeftToRight;
else
staticTextPos -= scrollPixelDistance;
}
else if (currentDirection == ScrollDirection.LeftToRight)
{
if (staticTextPos > this.ClientSize.Width - stringSize.Width)
currentDirection = ScrollDirection.RightToLeft;
else
staticTextPos += scrollPixelDistance;
}
break;
} //Calculate the vertical position for the scrolling text
switch (verticleTextPosition)
{
case VerticleTextPosition.Top:
yPos = ;
break;
case VerticleTextPosition.Center:
yPos = (this.ClientSize.Height / ) - (stringSize.Height / );
break;
case VerticleTextPosition.Botom:
yPos = this.ClientSize.Height - stringSize.Height;
break;
}
} #region Mouse over, text link logic
private void EnableTextLink(RectangleF textRect)
{
Point curPt = this.PointToClient(Cursor.Position); //if (curPt.X > textRect.Left && curPt.X < textRect.Right
// && curPt.Y > textRect.Top && curPt.Y < textRect.Bottom)
if (textRect.Contains(curPt))
{
//Stop the text of the user mouse's over the text
if (stopScrollOnMouseOver)
scrollOn = false; this.Cursor = Cursors.Hand;
}
else
{
//Make sure the text is scrolling if user's mouse is not over the text
scrollOn = true; this.Cursor = Cursors.Default;
}
} private void ScrollingText_Click(object sender, System.EventArgs e)
{
//Trigger the text clicked event if the user clicks while the mouse
//is over the text. This allows the text to act like a hyperlink
if (this.Cursor == Cursors.Hand)
OnTextClicked(this, new EventArgs());
} public delegate void TextClickEventHandler(object sender, EventArgs args);
public event TextClickEventHandler TextClicked; private void OnTextClicked(object sender, EventArgs args)
{
//Call the delegate
if (TextClicked != null)
TextClicked(sender, args);
}
#endregion #region Properties
[
Browsable(true),
CategoryAttribute("Scrolling Text"),
Description("The timer interval that determines how often the control is repainted")
]
public int TextScrollSpeed
{
set
{
timer.Interval = value;
}
get
{
return timer.Interval;
}
} [
Browsable(true),
CategoryAttribute("Scrolling Text"),
Description("How many pixels will the text be moved per Paint")
]
public int TextScrollDistance
{
set
{
scrollPixelDistance = value;
}
get
{
return scrollPixelDistance;
}
} [
Browsable(true),
CategoryAttribute("Scrolling Text"),
Description("The text that will scroll accros the control")
]
public string ScrollText
{
set
{
text = value;
this.Invalidate();
this.Update();
}
get
{
return text;
}
} //[
//Browsable(true),
//CategoryAttribute("Scrolling Text"),
//Description("What direction the text will scroll: Left to Right, Right to Left, or Bouncing")
//]
//public ScrollDirection ScrollDirection
//{
// set
// {
// scrollDirection = value;
// }
// get
// {
// return scrollDirection;
// }
//} //[
//Browsable(true),
//CategoryAttribute("Scrolling Text"),
//Description("The verticle alignment of the text")
//]
//public VerticleTextPosition VerticleTextPosition
//{
// set
// {
// verticleTextPosition = value;
// }
// get
// {
// return verticleTextPosition;
// }
//} [
Browsable(true),
CategoryAttribute("Scrolling Text"),
Description("Turns the border on or off")
]
public bool ShowBorder
{
set
{
showBorder = value;
}
get
{
return showBorder;
}
} [
Browsable(true),
CategoryAttribute("Scrolling Text"),
Description("The color of the border")
]
public Color BorderColor
{
set
{
borderColor = value;
}
get
{
return borderColor;
}
} //[
//Browsable(true),
//CategoryAttribute("Scrolling Text"),
//Description("Determines if the text will stop scrolling if the user's mouse moves over the text")
//]
//public bool StopScrollOnMouseOver
//{
// set
// {
// stopScrollOnMouseOver = value;
// }
// get
// {
// return stopScrollOnMouseOver;
// }
//} [
Browsable(true),
CategoryAttribute("Behavior"),
Description("Indicates whether the control is enabled")
]
new public bool Enabled
{
set
{
timer.Enabled = value;
base.Enabled = value;
} get
{
return base.Enabled;
}
} [
Browsable(false)
]
public Brush ForegroundBrush
{
set
{
foregroundBrush = value;
}
get
{
return foregroundBrush;
}
} [
ReadOnly(true)
]
public Brush BackgroundBrush
{
set
{
backgroundBrush = value;
}
get
{
return backgroundBrush;
}
}
#endregion
} public enum ScrollDirection
{
RightToLeft,
LeftToRight,
TopToBottom,
BottomToTop,
Bouncing
} public enum VerticleTextPosition
{
Top,
Center,
Botom
}
}
C# 文字滚动特效(上下滚动)的更多相关文章
- 滚动变色的文字js特效
Js实现滚动变色的文字效果,在效果展示页面,可看到文字在交替变色显示,以吸引人的注意,效果真心不错哦,把代码拷贝到你的网站后,修改成想要的文字就OK了. 查看效果:http://keleyi.com/ ...
- jquery插件之文字间歇自动向上滚动
该插件乃本博客作者所写,目的在于提升作者的js能力,也给一些js菜鸟在使用插件时提供一些便利,老鸟就悠然地飞过吧. 此插件旨在实现目前较为流行的文字间歇向上滚动特效,当鼠标移动到文字上时,向上滚动会停 ...
- jquery 文字滚动大全 scroll 支持文字或图片 单行滚动 多行滚动 带按钮控制滚动
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- jquery版楼层滚动特效
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>楼 ...
- Sequence.js 实现带有视差滚动特效的图片滑块
Sequence.js 功能齐全,除了能实现之前分享过的现代的图片滑动效果,还可以融合当前非常流行的视差滚动(Parallax Scrolling)效果.让多层背景以不同的速度移动,形成立体的运动效果 ...
- 一款非常炫酷的jQuery动态随机背景滚动特效
一款非常炫酷的jQuery动态随机背景滚动特效 图片背景会不停息的滚动,带有那种漂浮的视觉效果,小圈圈飘动. 更好的是还兼容IE6浏览器,大伙可以好好研究研究. 适用浏览器:IE6.IE7.IE8.3 ...
- jquery 单行滚动、批量多行滚动、文字图片翻屏滚动效果代码
jquery单行滚动.批量多行滚动.文字图片翻屏滚动效果代码,需要的朋友可以参考下. 以下代码,运行后,需要刷新下,才能加载jquery,要不然看不到效果.一.单行滚动效果 <!DOCTYPE ...
- 原生js实现tab选项卡里内嵌图片滚动特效代码
<!DOCTYPE HTML><html lang="en-US"><head><meta charset="UTF-8&quo ...
- 文字列表无缝向上滚动JavaScript代码
<!DOCTYPE html> <html> <head> <meta charset=utf-> <title>文字列表无缝向上滚动Jav ...
- JQ滚动特效
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8&quo ...
随机推荐
- Netty 服务端启动过程
在 Netty 中创建 1 个 NioServerSocketChannel 在指定的端口监听客户端连接,这个过程主要有以下 个步骤: 创建 NioServerSocketChannel 初始化并注 ...
- 2018-2019-2 网络对抗技术 20165228 Exp5 MSF基础应用
2018-2019-2 网络对抗技术 20165228 Exp5 MSF基础应用 exploit选取 主动攻击:ms17_010_eternalblue(唯一) 浏览器攻击:ms05_054_onlo ...
- jupyter notebook添加虚拟环境
原本以为,当进入虚拟环境之后,再运行jupyter notebook应该是这个环境下的jupyter,比如我默认创建一个文件,这个文件调用的编译器应该是这个虚拟环境中的编译器,实际上并不是 当你进入j ...
- 局部变量,全局变量初始值问题----C与指针练习题4.14.1
全局变量初始化0 局部变量初始化是随机值 如下面一段代码,全局变量,将src复制n个字符到dst #include<stdio.h> void copy_n(char dst[],char ...
- spring源码1:基本概念
一.预习 1.如何用spring?零配置(注解)或少配置,与应用无侵入性一起运行,与主流框架无缝集成. 2.spring 是什么?spring 是 java 企业应用级框架,目的是为了简化开发:主要体 ...
- s21day23 python笔记
s21day23 python笔记 一.内容回顾及补充 字符串格式化 %s # 示例一:特别注意:最后的右括号前面必须有逗号(,) msg = '我是%s,年龄%s'%('alex',19,) # 元 ...
- s21day15 python笔记
s21day15 python笔记 一.内容回顾及补充 回顾 补充 range / xrange(python2与python3的区别六) python2: xrange:不会在内存中立即创建,而是在 ...
- 2082 : Only choose one
题目描述 A想玩个游戏,游戏规则是,有n个人,编号从1-n,一字排开,站在奇数位置的人淘汰,剩下的人再一字排开,站在奇数位置的人淘汰,以此重复几次,最后只剩最后一个人,问最后一个人的编号是多少? 输入 ...
- PHP连接mysql数据库报错:Call to undefined function mysql_connect()
http://php.net/manual/zh/intro.mysqli.php 系统环境PHP7.0+Mysql5.7+Apache2. 运行一个数据库连接测试示例时报错: [client 127 ...
- pycharm+pydesigner+pyqt5 如何添加图片资源
pydesigner 上添加资源比较容易: 步骤一用于编辑,步骤二步创建,步骤三创建文件新的qrc: 步骤一:新建一个Prefix,步骤二给prefix添加资源文件.至此,资源文件添加完成 采用 Py ...