首页 > 代码库 > How-to:绘制换行文本的两种方法

How-to:绘制换行文本的两种方法

技术分享

第一种方法:用GDI+在矩形中绘制换行文本

技术分享
 1 private void btnGDIPlusMethod_Click(object sender, EventArgs e)
 2 {
 3             this.pictureBox1.Image = new Bitmap(this.pictureBox1.Width, this.pictureBox1.Height);
 4             Graphics g = Graphics.FromImage(this.pictureBox1.Image);
 5             g.Clear(Color.Black);
 6             string showText = "春秋左传公羊传榖梁传周易诗经尚书仪礼礼记周礼大学论语孟子中庸老子庄子荀子"+
 7                                         "管子国语新书楚辞搜神记昭明文选陶渊明集";
 8             using ( Font fnt = new Font("微软雅黑",24,FontStyle.Bold,GraphicsUnit.Pixel))
 9             {
10                 Rectangle rect = new Rectangle(0,0,this.pictureBox1.Width-1,this.pictureBox1.Height-1);
11                 g.DrawString(showText,fnt,Brushes.Green,rect,StringFormat.GenericTypographic);
12                 g.DrawRectangle(Pens.Red,Rectangle.Round(rect));
13             }
14 }
方法一

第二种方法:用GDI在矩形中绘制换行文本

技术分享
 1 private void btnGDIMethod_Click(object sender, EventArgs e)
 2 {
 3             this.pictureBox2.Image = new Bitmap(this.pictureBox2.Width, this.pictureBox2.Height);
 4             Graphics g = Graphics.FromImage(this.pictureBox2.Image);
 5             g.Clear(Color.Black);
 6             string showText = "春秋左传公羊传榖梁传周易诗经尚书仪礼礼记周礼大学论语孟子中庸老子庄子荀子"+
 7                                         "管子国语新书楚辞搜神记昭明文选陶渊明集";
 8             using (Font fnt = new Font("微软雅黑", 24, FontStyle.Bold, GraphicsUnit.Pixel))
 9             {
10                 TextFormatFlags tff = TextFormatFlags.WordBreak | TextFormatFlags.NoPadding;
11                 Rectangle rect = new Rectangle(0, 0, this.pictureBox2.Width - 1, this.pictureBox2.Height - 1);
12                 TextRenderer.DrawText(g, showText, fnt, rect, Color.Green, tff);
13                 g.DrawRectangle(Pens.Red, Rectangle.Round(rect));
14             }
15 }
方法二

How-to:绘制换行文本的两种方法