如何使用.Net 2.0绘制混合格式的文本

时间:2010-05-03 13:17:32

标签: text .net-2.0 system.drawing

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

的东西
System.Drawing.Graphics.DrawString()

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

非常感谢!
奥利弗

2 个答案:

答案 0 :(得分:1)

我正在书中提到答案WPF in Action - 您似乎有两个选择:

  
      
  • 创建自定义控件并定义自己的标记以指定字体。除了这需要很多工作之外,你还必须依靠众所周知的不准确的方法来测量文本的宽度(以便你可以找出下一个单词的位置)。

  •   
  • 使用RTF控件。这非常沉重,你最终会花费大量时间使它看起来像文本而不是编辑控件,你必须使用RTF来获得你想要的文本。

    < / LI>   

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

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

修改

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

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

这是一个链接,应该向您展示如何将GDI +与Bitmap / Image一起使用: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 +。

答案 1 :(得分: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中) 和你一起玩。