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

14 篇文章 0 订阅

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

复制代码
    
    
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 }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值