1 year ago

#359737

test-img

ilCosmico

How to convert Unicode text into a Bitmap

I need to convert a text containing Unicode chars into a Bitmap that could have a transparent background as well. I found and tried different posts like this, this, or this, but no one seems to work for me. I found also this post that suggests using TextRenderer.DrawText() method instead of System.Drawing.Graphics.DrawString() but the final result is not good anyway.

That's a code snippet:

private static Bitmap ImageFromText(string text, Font font, Color textColor, Color fillColor, System.Drawing.Graphics graphics)
{
    Bitmap bmpOut;

    SizeF sz = TextRenderer.MeasureText(graphics, text, font);
    //SizeF sz = g.MeasureString(text, font);

    if (sz.IsEmpty)

        sz = new SizeF(1, 1);

    bmpOut = new Bitmap((int) Math.Ceiling(sz.Width), (int) Math.Ceiling(sz.Height), PixelFormat.Format32bppArgb);
    using (System.Drawing.Graphics gBmp = System.Drawing.Graphics.FromImage(bmpOut))
    {
        gBmp.Clear(fillColor);

        gBmp.SmoothingMode = SmoothingMode.HighQuality;
        gBmp.InterpolationMode = InterpolationMode.HighQualityBilinear;
        gBmp.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

        //gBmp.DrawString(text, font, brFore, 0, 0); // Unicode chars are not supported
        TextRenderer.DrawText(gBmp, text, font, new Point(0, 0), textColor);
    }

    return bmpOut;
}

Here is my test code:

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();                
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        string testString = "Unicode Title \uD83E\uDC25";
        var font = new Font(new FontFamily("Microsoft Sans Serif"), 12.375f);

        // e.Graphics.DrawString(testString, new Font(font.FontFamily, 20), new SolidBrush(Color.Black), 0, 0);

        TextRenderer.DrawText(e.Graphics, testString, new Font ( font.FontFamily, 20 ), new Point(0, 50), Color.Black);

        Bitmap bitmap = ImageFromText(testString, new Font(font.FontFamily, 20), Color.Black, this.BackColor, e.Graphics);

        e.Graphics.DrawImage(bitmap, new Point(0, 100));                

        //Clipboard.SetImage(bitmap);

        
    }
}

And this is the poor result:

enter image description here

How can I improve the bitmap result?

EDIT

Short recap:

  • I can't use System.Drawing.Graphics.DrawString() method because it does not support Unicode chars
  • I can't use TextRenderer.DrawText() method because TextRenderer class uses GDI and it isn't alpha aware, so it does not support a transparent background.

Is there some other way to reach my goal?

c#

.net

bitmap

drawtext

drawstring

0 Answers

Your Answer

Accepted video resources