虽然font一般翻译为字体,但是实际在vs中,font包括很多方面的内容,常用的有:
Name:字体名称
Unit:度量单位,包括Point(打印机点,1/72 英寸)、Pixel(像素)等
Size:以设置的Unit为单位的字体大小
Bold:是否设置为粗体
Italic:是否设置为斜体
Underline:是否设置下划线
Strikeout:是否设置删除线(文字中间有一横线)
新建一个窗体,增加一个Button控件,Name为btnFont,Text为字体测试 。
按下btnFont的代码如下:
Private Sub btnFont_Click(sender As Object,e As EventArgs) Handles btnFont.Click '定义一个Font Dim f As Font '字体为隶书,大小20,粗体,以点为单位 f = New Font("隶书",20,FontStyle.Bold,GraphicsUnit.Point) '定义一个Label Dim lblshowFont As New Label lblshowFont.AutoSize = True lblshowFont.Top = 10 lblshowFont.Left = 10 lblshowFont.Text = "字体测试:" & f.Name lblshowFont.Font = f '动态加载这个Label Me.Controls.Add(lblshowFont) End Sub
运行如下:
接下来做个比刚才复杂的动作,在文字一周画个边框,
Private Sub btnDrawFont_Click(sender As Object,e As EventArgs) Handles btnDrawFont.Click '定义一个Font Dim f As Font '字体为隶书,大小20,粗体,以点为单位 f = New Font("隶书",GraphicsUnit.Point) '需要绘制的文本 Dim strDrawText As String = "字体测试:" & f.Name '方法1:Graphics.MeasureString '此方法返回 SizeF 结构,该结构表示 text 参数指定的、使用 font 参数绘制的字符串的大小,单位由 PageUnit 属性指定。--Msdn Dim sizeDrawText1 As SizeF Dim posDrawText1 As New Point(10,50) Dim g As Graphics = Me.CreateGraphics sizeDrawText1 = g.MeasureString(strDrawText,f) g.DrawString(strDrawText,f,New SolidBrush(Color.Red),posDrawText1) g.DrawRectangle(New Pen(Color.Blue),posDrawText1.X,posDrawText1.Y,sizeDrawText1.Width,sizeDrawText1.Height) '方法2:TextRenderer.MeasureText '使用指定字体进行绘制时测量指定的文本。--Msdn Dim posDrawText2 As New Point(10,90) Dim sizeDrawtext2 As SizeF = TextRenderer.MeasureText(strDrawText,posDrawText2) g.DrawRectangle(New Pen(Color.Green),posDrawText2.X,posDrawText2.Y,sizeDrawtext2.Width,sizeDrawtext2.Height) '方法2扩展:增加TextFormatFlags.NoPadding参数 Dim posDrawText3 As New Point(10,130) Dim sizeDrawtext3 As SizeF = TextRenderer.MeasureText(g,strDrawText,New Size(Integer.MaxValue,Integer.MaxValue),TextFormatFlags.NoPadding) g.DrawString(strDrawText,posDrawText3) g.DrawRectangle(New Pen(Color.Green),posDrawText3.X,posDrawText3.Y,sizeDrawtext3.Width,sizeDrawtext3.Height) '附带输出了各个方法获得文字长宽的信息 txtInfo.Text = "字体高度:" & f.Height & ControlChars.CrLf txtInfo.Text &= "使用MeasureString:" & ControlChars.CrLf txtInfo.Text &= "高度:" & sizeDrawText1.Height & ControlChars.CrLf txtInfo.Text &= "宽度:" & sizeDrawText1.Width & ControlChars.CrLf txtInfo.Text &= "使用TextRenderer:" & ControlChars.CrLf txtInfo.Text &= "高度:" & sizeDrawtext2.Height & ControlChars.CrLf txtInfo.Text &= "宽度:" & sizeDrawtext2.Width & ControlChars.CrLf txtInfo.Text &= "加上TextFormatFlags.NoPadding:" & ControlChars.CrLf txtInfo.Text &= "高度:" & sizeDrawtext3.Height & ControlChars.CrLf txtInfo.Text &= "宽度:" & sizeDrawtext3.Width & ControlChars.CrLf g.Dispose() End Sub
运行如下:
相比较下,第二种方法的扩展形态要适合一些。当然具体问题具体分析,还要看实际情况。
由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供的参考。
学习更多vb.net知识,请参看 vb.net 教程 目录
原文链接:https://www.f2er.com/vb/256790.html