C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#迭代器动态文字

C#使用迭代器实现动态文字效果

作者:yue008

这篇文章主要介绍了如何使用C#的Drawing空间和Panel控件实现动态文字效果,通过设置字体参数、创建画布、使用Graphics类的FillRectangle, MeasureString和DrawString方法,以及Panel控件的CreateGraphics方法,实现在Panel上绘制动态文字,需要的朋友可以参考下

本文主介绍如何使用C#实现动态文字效果。效果图如下

实现方式

使用Drawing空间下的类,将文字重绘制,并输出到Panel控件的画布中
1、设定相关参数,字体大小、字体样式、字体颜色、控件的宽度和高度、字体的宽度和高度、以及单个文字的宽度
2、在Panel控件中创建画布,并获取控件的高度、宽度、背景颜色,以及文字的高度、宽度,并设置绘制字体的样式,包括高度、宽度以及字体规格等等。

知识点

Graphics

封装一个 GDI+ 绘图图面。 此类不能被继承,属于System.Drawing命名空间。通俗来说,就是一块画布
本项目用到此类的方法属性主要有:

FillRectangle:

public void FillRectangle(System.Drawing.Brush brush, float x, float y, float width, float height);

FillRectangle(Brush, Single, Single, Single, Single)

参数类型说明
brushBrush定义用于填充图形形状(如矩形、椭圆、饼形、多边形和封闭路径)的内部的对象
XSingle要填充的矩形左上角的 x 坐标
YSingle要填充的矩形左上角的 y 坐标
widthSingle要填充的矩形的宽度
heightSingle要填充的矩形的高度

填充由一对坐标、宽度和高度指定的矩形的内部。

System.Drawing.Graphics g;//定义Graphics对象
 g= C_Panel.CreateGraphics();
 g.FillRectangle(new SolidBrush(Panel_C), 0, 0, Panel_W, Panel_H);//用控件背景填充控件

MeasureString

用指定的 Font绘制时度量指定的字符串。
MeasureString(String, Font)
String:要度量的字符串
Font:定义字符串文本格式的 Font。
此方法返回一个 SizeF 结构,该结构代表用 font 参数绘制的由 text 参数指定的字符串的大小

SizeF TitSize = g.MeasureString(C_str, Str_Font);//将绘制的字符串进行格式化
Str_Width = TitSize.Width;//获取字符串的宽度
Str_Height = TitSize.Height;//获取字符串的高度
Str_Odd_Width=Str_Width /(float)C_str.Length;//获取单个文字的高度
Str_Width = (float)((Str_Odd_Width + Str_block) * C_str.Length);//获取文字的宽度
Str_Width = (Panel_W - Str_Width) / 2F;//使文字居中
Str_Height = Panel_H - Str_Height;//使文字显示在控件底端

DrawString

使用指定的 Brush 和 Font 对象在指定位置绘制指定的文本字符串

public void DrawString (string? s, System.Drawing.Font font, System.Drawing.Brush brush, System.Drawing.PointF point);

参数 s String 要绘制的字符串。
font Font 定义字符串文本格式的 Font。
brush Brush 确定所绘制文本的颜色和纹理的 Brush。
point PointF PointF 指定绘制文本左上角的结构。

public void DrawStringPointF(PaintEventArgs e)
{
             
    // Create string to draw.
    String drawString = "Sample Text";
             
    // Create font and brush.
    Font drawFont = new Font("Arial", 16);
    SolidBrush drawBrush = new SolidBrush(Color.Black);
             
    // Create point for upper-left corner of drawing.
    PointF drawPoint = new PointF(150.0F, 150.0F);
             
    // Draw string to screen.
    e.Graphics.DrawString(drawString, drawFont, drawBrush, drawPoint);
}

Font

定义特定的文本格式,包括字体、字号和样式特性。 此类不能被继承。
属于System.Drawing命名空间。通俗来说,就是一个画布上的字体
通过构造函数,传入字体参数,然后将Font类作为参数,再传入到SolidBrush类。
Font(FontFamily, Single, FontStyle)
FontFamily:字体种类,黑体,宋体等等
Single:字体大小
FontStyle:字体类型,斜体、黑体等等

Font Tem_Font = new Font("黑体", FSize[0], FontStyle.Bold);//定义字体样式
Graphics .DrawString(C_Odd_Str, S_Font, new SolidBrush(Str_Color), new PointF(left,top));//绘制字符串中单个文字

SizeF

存储有序浮点数对,通常为矩形的宽度和高度

private void AddShadow(PaintEventArgs e)
{

    // Create two SizeF objects.
    SizeF shadowSize = listBox1.Size;
    SizeF addSize = new SizeF(10.5F, 20.8F);

    // Add them together and save the result in shadowSize.
    shadowSize = shadowSize + addSize;

    // Get the location of the ListBox and convert it to a PointF.
    PointF shadowLocation = listBox1.Location;

    // Add two points to get a new location.
    shadowLocation = shadowLocation + new Size(5, 5);

    // Create a rectangleF. 
    RectangleF rectFToFill = 
        new RectangleF(shadowLocation, shadowSize);

    // Create a custom brush using a semi-transparent color, and 
    // then fill in the rectangle.
    Color customColor = Color.FromArgb(50, Color.Gray);
    SolidBrush shadowBrush = new SolidBrush(customColor);
    e.Graphics.FillRectangles(shadowBrush, new RectangleF[]{rectFToFill});

    // Dispose of the brush.
    shadowBrush.Dispose();
}

PointF

表示在二维平面中定义点的浮点 x 和 y 坐标的有序对。
构造函数:PointF(Single, Single)

public PointF (float x, float y);

x Single 该点的水平位置。
y Single 该点的垂直位置。

public void DrawStringPointF(PaintEventArgs e)
{
             
    // Create string to draw.
    String drawString = "Sample Text";
             
    // Create font and brush.
    Font drawFont = new Font("Arial", 16);
    SolidBrush drawBrush = new SolidBrush(Color.Black);
             
    // Create point for upper-left corner of drawing.
    PointF drawPoint = new PointF(150.0F, 150.0F);
             
    // Draw string to screen.
    e.Graphics.DrawString(drawString, drawFont, drawBrush, drawPoint);
}

SolidBrush

定义单色画笔。 画笔用于填充图形形状,如矩形、椭圆、扇形、多边形和封闭路径。 此类不能被继承。
构造函数:SolidBrush(Color)

public void CartoonEffect(Panel C_Panel,string C_Str)
{
    g= C_Panel.CreateGraphics();//在panel控件中创建画布,即Graphics
    Panel_H = C_Panel.Height;
    Panel_W = C_Panel.Width;
    Panel_C=C_Panel.BackColor;
    GetTextInfo(C_Str);
    g.FillRectangle(new SolidBrush(Panel_C), 0, 0, Panel_W, Panel_H);//用控件背景填充控件
    ProtractText(C_Str, 0);//绘制文字
    th=new Thread(new ParameterizedThreadStart(DynamicText));
    th.Start(C_Str);

   
}

Panel控件

方法:CreateGraphics
创建画布

System.Drawing.Graphics g;//定义Graphics对象
g= C_Panel.CreateGraphics();//在panel控件中创建画布,即Graphics

线程

Thread

ParameterizedThreadStart 委托
表示在 Thread 上执行的方法。

public delegate void ParameterizedThreadStart(object? obj);

obj:包含线程过程的数据的对象。

using System;
using System.Threading;

public class Work
{
    public static void Main()
    {
        // Start a thread that calls a parameterized static method.
        Thread newThread = new Thread(Work.DoWork);
        newThread.Start(42);

        // Start a thread that calls a parameterized instance method.
        Work w = new Work();
        newThread = new Thread(w.DoMoreWork);
        newThread.Start("The answer.");
    }
 
    public static void DoWork(object data)
    {
        Console.WriteLine("Static thread procedure. Data='{0}'",
            data);
    }

    public void DoMoreWork(object data)
    {
        Console.WriteLine("Instance thread procedure. Data='{0}'",
            data);
    }
}
// This example displays output like the following:
//       Static thread procedure. Data='42'
//       Instance thread procedure. Data='The answer.'

迭代

public static IEnumerable<object> Transpose(string n)
{
	if(n.Length>0)  //如果泛型不为空
      {
         foreach(object i in n) //对字符串进行遍历
           {
	               yield return i;
           }
        }
}


foreach(object s in Transpose(C_Str.ToString()))
{
		ProtractOddText(s.ToString(), Tem_Font, tem_left, tem_top);//绘制单个文字
}

画面组态

控件:Panel控件

代码解析

    private void Form1_Load(object sender, EventArgs e)
    {
        Graphics Car_Paint = panel1.CreateGraphics();//实例化绘图对象
        string Car_Str = "你好,你在哪呢";
        Character character = new Character();//实例化自定义类对象
        character.CartoonEffect(panel1, Car_Str);//在窗体上显示动态文字
    }

    class Character
    {
        System.Drawing.Graphics g;//定义Graphics对象
        static int[] FSize = new int[3] { 20, 25, 30 };//设置字体的大小
        int Str_block = 5;//字体间隔时间
        Font Str_Font = new Font("宋体", FSize[0], FontStyle.Bold);//定义字体样式
        Color Str_Color = Color.Orange;//定义字体颜色
        float Str_Width = 0;//获取字符串的位置
        float Str_Height = 0;
        float Panel_W = 0;//获取控件的宽度
        float Panel_H = 0;//获取控件的高度
        Color Panel_C;//记录控件的背景颜色
        float Str_Odd_Width = 0;//获取单个文字的宽度
        Thread th;//定义线程

        public void CartoonEffect(Panel C_Panel,string C_Str)
        {
            g= C_Panel.CreateGraphics();//在panel控件中创建画布,即Graphics
            Panel_H = C_Panel.Height;
            Panel_W = C_Panel.Width;
            Panel_C=C_Panel.BackColor;
            GetTextInfo(C_Str);
            g.FillRectangle(new SolidBrush(Panel_C), 0, 0, Panel_W, Panel_H);//用控件背景填充控件
            ProtractText(C_Str, 0);//绘制文字
            th=new Thread(new ParameterizedThreadStart(DynamicText));
            th.Start(C_Str);

           
        }

        /// <summary>
        /// 获取文字的大小及绘制位置
        /// </summary>
        /// <param name="C_str">文字字符串</param>
        public void GetTextInfo(string C_str)
        {
            SizeF TitSize = g.MeasureString(C_str, Str_Font);//将绘制的字符串进行格式化
            Str_Width = TitSize.Width;//获取字符串的宽度
            Str_Height = TitSize.Height;//获取字符串的高度
            Str_Odd_Width=Str_Width /(float)C_str.Length;//获取单个文字的高度
            Str_Width = (float)((Str_Odd_Width + Str_block) * C_str.Length);//获取文字的宽度
            Str_Width = (Panel_W - Str_Width) / 2F;//使文字居中
            Str_Height = Panel_H - Str_Height;//使文字显示在控件底端

        }
        public void ProtractText(string C_Str,int n)
        {
            float Str_Place = Str_Width;//单个字符的位置
            for(int i=0;i<C_Str.Length;i++)
            {
                if(i!=n)
                {
                    ProtractOddText(C_Str[i].ToString(), Str_Font, Str_Place, Str_Height);//绘制单个文字
                    Str_Place += Str_Odd_Width + Str_block;//获取下一个文字的位置
                }
            }

        }
        public void ProtractOddText(string C_Odd_Str,Font S_Font,float left,float top)
        {
            g.DrawString(C_Odd_Str, S_Font, new SolidBrush(Str_Color), new PointF(left,top));//绘制字符串中单个文字
        }

        public static IEnumerable<object> Transpose(string n)
        {
            if(n.Length>0)  //如果泛型不为空
            {
                foreach(object i in n) //对字符串进行遍历
                {
                    yield return i;
                }
            }
        }

        public void DynamicText(object C_Str)
        {
            float tem_left = 0;//获取当前文字的左端位置
            float tem_top = 0;//获取当前文字的顶端位置
            float tem_W = 0;
            float tem_H = 0;
            float tem_place = Str_Width;//获取起始文字的位置
            Font Tem_Font = new Font("黑体", FSize[0], FontStyle.Bold);//定义字体样式
            int p = 0;//记录字符串中文字的索引号
            int Str_Index = 0;
            try
            {
                foreach(object s in Transpose(C_Str.ToString()))
                {
                    for(int i=1;i<5;i++)
                    {
                        if (i >= 3)
                        {
                            p = Convert.ToInt16(Math.Floor(i / 2F));
                        }
                        else
                            p = i;
                        ProtractText(C_Str.ToString(), Str_Index);
                        Tem_Font = new Font("黑体", FSize[p], FontStyle.Bold);//定义字体样式
                        SizeF TitSize = g.MeasureString(s.ToString(), Str_Font);//将绘制的单个文字进行格式化
                        tem_W = TitSize.Width;//获取文字的宽度
                        tem_H = TitSize.Height;//获取文字的高度
                        tem_left = tem_place - (tem_W - Str_Odd_Width) / 2F;//获取文字改变大小后的左端位置
                        tem_top = Str_Height - (Str_Height - tem_H) / 2F;
                        ProtractOddText(s.ToString(), Tem_Font, tem_left, tem_top);//绘制单个文字
                        Thread.Sleep(200);//等待0.2秒
                        g.FillRectangle(new SolidBrush(Panel_C), 0, 0, Panel_W, Panel_H);
                    }
                    tem_place += Str_Odd_Width + Str_block;//计算下一个文字的左端位置
                    Str_Index += 1;
                }
                ProtractText(C_Str.ToString(), -1);//恢复文字的原始绘制样式
                th = new Thread(new ParameterizedThreadStart(DynamicText));
                th.Start(C_Str);
            }
            catch
            {
                th.Abort();
            }
        }
    }
}

文字绘制

  private void Form1_Load(object sender, EventArgs e)
{
Graphics Car_Paint = panel1.CreateGraphics();//实例化绘图对象
string Car_Str = "你好,你在哪呢";
Character character = new Character();//实例化自定义类对象
character.CartoonEffect(panel1, Car_Str);//在窗体上显示动态文字
}

class Character
{
System.Drawing.Graphics g;//定义Graphics对象
static int[] FSize = new int[3] { 20, 25, 30 };//设置字体的大小
int Str_block = 5;//字体间隔时间
Font Str_Font = new Font("宋体", FSize[0], FontStyle.Bold);//定义字体样式
Color Str_Color = Color.Orange;//定义字体颜色
float Str_Width = 0;//获取字符串的位置
float Str_Height = 0;
float Panel_W = 0;//获取控件的宽度
float Panel_H = 0;//获取控件的高度
Color Panel_C;//记录控件的背景颜色
float Str_Odd_Width = 0;//获取单个文字的宽度

public void CartoonEffect(Panel C_Panel,string C_Str)
{
	g= C_Panel.CreateGraphics();//在panel控件中创建画布,即Graphics
	Panel_H = C_Panel.Height;
	Panel_W = C_Panel.Width;
	Panel_C=C_Panel.BackColor;
	GetTextInfo(C_Str);
	g.FillRectangle(new SolidBrush(Panel_C), 0, 0, Panel_W, Panel_H);//用控件背景填充控件
	ProtractText(C_Str, 0);//绘制文字
}

/// <summary>
/// 获取文字的大小及绘制位置
/// </summary>
/// <param name="C_str">文字字符串</param>
public void GetTextInfo(string C_str)
{
	SizeF TitSize = g.MeasureString(C_str, Str_Font);//将绘制的字符串进行格式化
	Str_Width = TitSize.Width;//获取字符串的宽度
	Str_Height = TitSize.Height;//获取字符串的高度
	Str_Odd_Width=Str_Width /(float)C_str.Length;//获取单个文字的高度
	Str_Width = (float)((Str_Odd_Width + Str_block) * C_str.Length);//获取文字的宽度
	Str_Width = (Panel_W - Str_Width) / 2F;//使文字居中
	Str_Height = Panel_H - Str_Height;//使文字显示在控件底端

}
public void ProtractText(string C_Str,int n)
{
	float Str_Place = Str_Width;//单个字符的位置
	for(int i=0;i<C_Str.Length;i++)
	{
		if(i!=n)
		{
			ProtractOddText(C_Str[i].ToString(), Str_Font, Str_Place, Str_Height);//绘制单个文字
			Str_Place += Str_Odd_Width + Str_block;//获取下一个文字的位置
		}
	}

}
public void ProtractOddText(string C_Odd_Str,Font S_Font,float left,float top)
{
	g.DrawString(C_Odd_Str, S_Font, new SolidBrush(Str_Color), new PointF(left,top));//绘制字符串中单个文字
}

以上就是C#使用迭代器实现动态文字效果的详细内容,更多关于C#迭代器动态文字的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文