使用Font類繪製文本(DrawString())

本文通过一个实例展示了如何使用GDI+在窗体上绘制不同格式的文本,包括左对齐、右对齐、居中显示以及换行显示等效果,并详细介绍了绘制过程中的关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

代碼如下:

public partial class Stringformat : Form
    
{
        
public Stringformat()
        
{
            InitializeComponent();

            SetStyle(ControlStyles.Opaque, 
true);
            Point p 
= new Point(00);
            Size s 
= new Size(500300);
            
//Bounds = new Rectangle(0, 0, 500, 300);
            Bounds = new Rectangle(p, s);//窗體大小及相對於父客體的位置(0,0)
        }

        
protected override void OnPaint(PaintEventArgs e)//重定義基類OnPaint()方法
        {
            Graphics g 
= e.Graphics;
            
int y = 0;
            g.FillRectangle(Brushes.White, ClientRectangle);
//繪制窗體背景色
            Rectangle rect = new Rectangle(0, y, 400, Font.Height);
            
//g.FillRectangle(Brushes.Blue, rect);//墳兗一個矩形
            g.DrawRectangle(Pens.Blue, rect);//繪製一個矩形
            g.DrawString("This text is left justified.", Font, Brushes.Black, rect);
            y 
+= Font.Height + 20;
            
//Font.Dispose();//沒有創建對象,無須釋放資源

            Font afont 
= new Font("Arial"16, FontStyle.Bold | FontStyle.Italic);
            rect 
= new Rectangle(0, y, 400, afont.Height);
            g.DrawRectangle(Pens.Blue, rect);
            StringFormat sf 
= new StringFormat();
            sf.Alignment 
= StringAlignment.Far;
            g.DrawString(
"This text is right justified.", afont, Brushes.Blue, rect,sf);
            y 
+= afont.Height + 20;
            afont.Dispose();
//創建了對象,須釋放資源

            afont 
= new Font("Courier Ncw"12, FontStyle.Underline|FontStyle.Bold);
            rect 
= new Rectangle(0, y, 400, afont.Height);
            g.DrawRectangle(Pens.Blue, rect);
            sf 
= new StringFormat();
            sf.Alignment 
= StringAlignment.Center;
            g.DrawString(
"This text is centered, and unederlined.", afont, Brushes.Blue, rect, sf);
            y 
+= afont.Height + 20;
            afont.Dispose();

            afont 
= new Font("Times New Roman"12);
            rect 
= new Rectangle(0, y, 400, afont.Height * 3);
            g.DrawRectangle(Pens.Blue, rect);
            
string longString = "This text is much longer, and drawn ";
            longString 
+= "into a rectangle that is higher than ";
            longString 
+= "one line,so that it will wrap. It is ";
            longString 
+= "very easy to wrap text using GDI+.";
            g.DrawString(longString, afont, Brushes.Black, rect);
            afont.Dispose();
        }

    }

 運行效果圖:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值