3

有没有办法在 .Net 2.0 中绘制混合格式的文本?我正在寻找类似的东西

System.Drawing.Graphics.DrawString()

我对这种方法的问题是它只允许整个文本使用一种格式样式。但我需要绘制具有不同格式样式的文本(例如,部分文本应加下划线,另一部分加粗等)。

非常感谢!
奥利弗

4

2 回答 2

1

我从《WPF in Action》一书中得到了答案——你似乎有两个选择:

  • 创建一个自定义控件并定义您自己的用于指定字体的标记。除了这项工作量很大之外,您还必须依靠众所周知的不准确的方法来测量文本的宽度(这样您就可以弄清楚下一个单词的放置位置)。

  • 使用 RTF 控件。这非常繁重,您最终会花费大量时间使其看起来像文本而不是编辑控件,并且您必须使用 RTF 才能以您想要的方式获取文本。

所以我想答案是 RTF 控件(又名RichTextBox),如果你坚持使用 .NET 2.0——WinForms。好吧,除非您想编写自己的控件... :-)

这本书还提到采用各种标签和/或文本框控件并手动(或以编程方式)对齐它们并设置为具有不同的字体值等。但我假设你想避免这种情况,对吧?

编辑

我将上面的答案留在原地。这是我给你的新答案:

查看 GDI+——这里是 C# Corner 教程的链接,它应该向您介绍 GDI+:http ://www.c-sharpcorner.com/uploadfile/mahesh/gdi_plus12092005070041am/gdi_plus.aspx

这是一个链接,应该向您展示如何将 GDI+ 与位图/图像一起使用:http: //ondotnet.com/pub/a/dotnet/2003/05/05/gdiplus.html

祝你好运!

另外,你可能想买一本关于这方面的书,因为 GDI+ 是一个相当沉重的话题。我通过Pro .NET 2.0 Windows Forms and Custom Controls in C#一书完成了有关 GDI+ 的大部分学习(根据我的经验,这是一本好书。)虽然由于您对为 WinForms 设计自定义控件并不完全感兴趣,但您可能想要寻找一本更直接面向 GDI+ 的书。

于 2010-05-03T13:39:32.907 回答
0

如果你想使用 HTML 来标记你的文本,试试这个:

Private Sub DrawHTMLString(sHTML As String, rct As RectangleF, dpiX As Single, dpiY As Single, g As Graphics)
    DrawHTMLString(sHTML, rct.X, rct.Y, rct.Width, rct.Height, dpiX, dpiY, g)
End Sub

Private Sub DrawHTMLString(sHTML As String, x As Single, y As Single, width As Single, height As Single, dpiX As Single, dpiY As Single, g As Graphics)
    g.InterpolationMode = InterpolationMode.NearestNeighbor
    g.SmoothingMode = SmoothingMode.AntiAlias
    g.CompositingQuality = CompositingQuality.AssumeLinear
    g.TextRenderingHint = TextRenderingHint.AntiAlias

    g.DrawImage(DrawHTMLString(sHTML, width, height, dpiX, dpiY), x, y)
End Sub

Private Function DrawHTMLString(sHTML As String, width As Single, height As Single, dpiX As Single, dpiY As Single) As Bitmap
    Dim bmp As Bitmap = Nothing
    Dim doc As HtmlDocument = Nothing

    Using wb As New WebBrowser()
        wb.ScrollBarsEnabled = False
        wb.ScriptErrorsSuppressed = True
        wb.Navigate("about:blank")

        wb.Width = width : wb.Height = height

        doc = wb.Document.OpenNew(True)
        doc.Write(sHTML)

        bmp = New Bitmap(wb.Width, wb.Height, PixelFormat.Format32bppArgb)
        bmp.SetResolution(dpiX, dpiY)

        wb.DrawToBitmap(bmp, New Rectangle(0, 0, wb.Width, wb.Height))
    End Using

    Return bmp
End Function

(抱歉,它在 VB.NET 中)随心所欲地使用它。

于 2013-07-18T23:46:45.080 回答