【问题标题】:How to draw mixed-formatted text with .Net 2.0如何使用 .Net 2.0 绘制混合格式的文本
【发布时间】:2013-07-19 07:46:45
【问题描述】:

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

System.Drawing.Graphics.DrawString()

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

非常感谢!
奥利弗

【问题讨论】:

  • 您正在寻找的是添加到 .NET 3.5(可能是 .NET 3.0?)的功能——我知道在 .NET 2.0 中没有本地方法可以做到这一点——可能有不过,一些第 3 方插件可以解决这个问题。

标签: text .net-2.0 system.drawing


【解决方案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+。

【讨论】:

  • 嗨,我的 RichTextBox 问题:我不想在应用程序中显示文本,但我想在 System.Drawing.Bitmap 对象上绘制它,然后将其另存为 PNG文件。我想过使用 RichTextBox 作为输入元素,但我不知道如何在 Bitmap 对象上绘制文本。
【解决方案2】:

如果你想使用 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 中) 随心所欲地玩它。

【讨论】:

    猜你喜欢
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    • 2010-12-07
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    相关资源
    最近更新 更多