在vb.net中绘制文本以匹配菜单项

时间:2014-04-24 11:07:51

标签: .net vb.net gdi+ drawstring toolstripmenu

我想在vb.net 2010中的菜单项的左边缘添加一个数字,但似乎只能将其设置为图像。所以,我一直在尝试使用Graphics.DrawString()创建一个包含我想要的数字的图像。我尝试了各种方法,但我不能让结果图像看起来像菜单项本身的文本 - 有没有办法做到这一点?这是我当前的代码(分配一个图像来测量文本,然后重新分配正确的大小是关于这个版本3 - 非常难看,但我不确定如何测量)。

mnuItem = New ToolStripMenuItem
numPeople = CInt(Math.Ceiling(Rnd() * 20))

' Calculate the size of the text
qImg = New Bitmap(1, 1)
sf.Alignment = StringAlignment.Center
sf.LineAlignment = StringAlignment.Center
gr = Graphics.FromImage(qImg)
gr.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias
sz = gr.MeasureString(numPeople, mnuItem.Font, New Point(0, 0), sf)
w = CInt(Math.Ceiling(sz.Width))
h = CInt(Math.Ceiling(sz.Height))
m = Math.Max(w, h)

' Now allocate an image of the correct size
qImg = New Bitmap(m, m)
gr = Graphics.FromImage(qImg)
gr.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias
gr.DrawString(numPeople, mnuItem.Font, Brushes.Black, New RectangleF((m - w) / 2, (m - h) / 2, w, h), sf)

mnuItem.Image = qImg

以下是一些示例: - 请注意边距文本(图像)与菜单项文本的比较模糊:

Example menu with fuzzy text Example menu with fuzzy text

我已经尝试了所有TextRenderingHint选项,有些选项比其他选项更好,但没有一个选项能够提供菜单文本的清晰外观。有没有办法接近这个样子?

2 个答案:

答案 0 :(得分:1)

这让我感到困惑了一段时间,我得出结论,这是一个错误,因为只要你添加背景颜色,文字就会按照你的意愿显示。

我有一个解决方案。它使用从Professional Colors类派生的渐变画笔在绘制文本之前在位图的背景中绘制一个矩形。

Dim mnuItem = TestToolStripMenuItem
Dim numPeople = CInt(Math.Ceiling(Rnd() * 20))

Dim qImg = New Bitmap(mnuItem.Height, mnuItem.Height)
Using gr = Graphics.FromImage(qImg)
    Dim sz = gr.MeasureString(numPeople, mnuItem.Font)

    Dim w = CInt(Math.Ceiling(sz.Width))
    Dim h = CInt(Math.Ceiling(sz.Height))

    Dim linGrBrush As New LinearGradientBrush( _
       New Point(0, 0), _
       New Point(qImg.Width, 0), _
       ProfessionalColors.ToolStripGradientBegin, _
       ProfessionalColors.ToolStripGradientEnd)

    gr.FillRectangle(linGrBrush, New Rectangle(0, 0, qImg.Width, qImg.Height))
    gr.DrawString(numPeople, mnuItem.Font, Brushes.Black, New Point((qImg.Width / 2) - (w / 2), (qImg.Height / 2) - (h / 2)))
End Using

mnuItem.Image = qImg

enter image description here

您需要在课程顶部的Imports System.Drawing.Drawing2D

答案 1 :(得分:1)

您是否尝试过创建自己的ToolStripMenuItem

Class CustomToolStripMenuItem
    Inherits System.Windows.Forms.ToolStripMenuItem
    Protected Overrides Sub OnPaint(e As System.Windows.Forms.PaintEventArgs)
        MyBase.OnPaint(e)
        e.Graphics.DrawString("11", Me.Font, System.Drawing.Brushes.Black, New System.Drawing.PointF(0, 0))
    End Sub
End Class

我没有做任何计算来正确显示它,但我认为你可以做到。在我的系统上看起来像这样(参见"另存为"项目)

enter image description here