4

我想在 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

以下是这给出的几个示例 - 请注意边距文本(图像)与菜单项文本相比有多模糊:

带有模糊文本的示例菜单 带有模糊文本的示例菜单

我已经尝试了所有TextRenderingHint选项,有些选项比其他选项更好,但没有一个选项能让菜单文本看起来清晰。有没有办法更接近这种外观?

4

2 回答 2

1

Have you tried with creating your own 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

I am NOT doing any calculation to correctly display it, but I think you can do it. It appears like this on my system (see the "Save As" item)

enter image description here

于 2014-04-29T15:00:00.887 回答
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

在此处输入图像描述

您将需要Imports System.Drawing.Drawing2D在班级顶部的行

于 2014-04-29T13:50:57.197 回答