C#--GDI+绘制多行文本和格式化文本

简介: 绘制多行文本需要计算行高,然后绘出字符串: 1 private void Form1_Paint(object sender, PaintEventArgs e) 2 { 3 Graphics g = e.

绘制多行文本需要计算行高,然后绘出字符串:

 
 
1 private void Form1_Paint( object sender, PaintEventArgs e)
2 {
3 Graphics g = e.Graphics;
4 g.FillRectangle(Brushes.White, this .ClientRectangle);
5 string s = " This string is long enough to wrap. " ;
6 s += " With a 200px-width rectangle,and a 12pt font. " ;
7 s += " it requires six lines to display the stirng in its entirety. " ;
8
9 Font f = new Font( " Arial " , 12 );
10 Rectangle r = new Rectangle( 20 , 20 , 200 , f.Height * 6 );
11 g.DrawRectangle(Pens.Black,r);
12 g.DrawString(s, f, Brushes.Black, r);
13
14 f.Dispose();
15 }

绘制竖向文本,需要指定StringFormat类为DirectionVertical,即:StringFormat sf = new StringFormat(StringFormatFlags.DirectionVertical);

然后应用于文字

    SizeF sizef = g.MeasureString(s, f, Int32.MaxValue, sf);

   // Create and draw the rectangle
   // Also draw the text string (using the StringFormat object)
   RectangleF rf = new RectangleF(20, 20, sizef.Width, sizef.Height);

代码如下:

 
 
1 private void Form1_Paint( object sender,
2 System.Windows.Forms.PaintEventArgs e)
3 {
4 Graphics g = e.Graphics;
5 g.FillRectangle(Brushes.White, this .ClientRectangle);
6
7 // Create a text string, a Font object, and a StringFormat object
8   String s = " Accrington Stanley " ;
9 StringFormat sf = new StringFormat(StringFormatFlags.DirectionVertical);
10 Font f = new Font( " Times New Roman " , 14 );
11
12 // Calculate the size of the text string's containing rectangle
13   SizeF sizef = g.MeasureString(s, f, Int32.MaxValue, sf);
14
15 // Create and draw the rectangle
16 // Also draw the text string (using the StringFormat object)
17 RectangleF rf = new RectangleF( 20 , 20 , sizef.Width, sizef.Height);
18 g.DrawRectangle(Pens.Black, rf.Left, rf.Top, rf.Width, rf.Height);
19 g.DrawString(s, f, Brushes.Black, rf, sf);
20
21 f.Dispose();
22 }
相关文章
|
C#
C#读取txt文本的行数
C#读取txt文本的行数
309 0
|
存储 API C#
C# 实现格式化文本导入到Excel
C# 实现格式化文本导入到Excel
|
存储 SQL 数据库
C# 将 Word 转文本存储到数据库并进行管理
C# 将 Word 转文本存储到数据库并进行管理
233 2
|
存储 SQL 数据库
C# 将 Word 转文本存储到数据库并进行管理
C# 将 Word 转文本存储到数据库并进行管理
|
开发框架 自然语言处理 文字识别
一款C#开发的窗口文本提取开源软件
一款C#开发的窗口文本提取开源软件
303 2
|
存储 C# C++
C# 笔记2 - 数组、集合与与文本文件处理
C# 笔记2 - 数组、集合与与文本文件处理
163 0
C# GDI+绘图(四)实现网格绘制,并填充相应的表格内容
C# GDI+绘图(四)实现网格绘制,并填充相应的表格内容
C# GDI+绘图(三)GDI+实现QQ截图类似功能
C# GDI+绘图(三)GDI+实现QQ截图类似功能
C# GDI+绘图(二)进阶---Pen/Brush以及坐标轴平移和旋转等
上一篇C# GDI+绘图(一)GDI+介绍及基础,我们介绍了,GDI+的基础,这篇我们对其进阶内容进行学习,分别为Pen/Brush以及坐标轴操作
|
C# 图形学
C# GDI+绘图(一)GDI+介绍及基础
最近,项目中,有一块比较发杂的网格,并在网格上绘有各种颜色和文本,在Dev库中并未找到能实现这种功能的现有或可以二次开发的控件,因此,涉及到GDI+绘图这块陌生的领域。下面即时我在本次学习过程中的笔记,本次内容一共分为4篇,分别都有各自的代码或工程文件提供,有需要的朋友可以下载。

热门文章

最新文章