简体   繁体   中英

Characters changing in Graphics.DrawString

I have a dll written in C#. One of the methods takes a parameter string txt . The dll is being called from a classic asp page. At the time of calling, the text contains the character é which is obtained by holding down ALT and typing 130 on the number pad or by holding down ALT-GR and hitting e .

The DrawString method is outputting it wrong. I realize there is a character set/font issue, but I don't know how to get round the problem.

What I get on a British keyboard and localization using Arial font is a capital A with a tilde above it followed by lowercase c in a circle.

The individual entering the text may be using any keyboard layout, may have any localization on their PC, but they will all be entering it via our web page.

What do I need to do to make things compatible or to convert?

The relevant bit of code is:

Bitmap image = new Bitmap(strFilePath);

Graphics m_graphics;
m_graphics = Graphics.FromImage(image);

Font fnt = new Font("Arial", 12.0f);

StringFormat strFormatter = new StringFormat();

SolidBrush txtBrush = new SolidBrush(Color.FromArgb(127, Color.FromArgb(int.Parse("AB12CD", NumberStyles.HexNumber))));

m_graphics.DrawString("é", fnt, txtBrush, new Point(200, 200), strFormatter);

As your string of text is coming from a web page, it could be URL encoded. Try decoding it first, and making sure the result is UTF8:

string strDecoded = HttpUtility.UrlDecode(strEncoded, Encoding.UTF8)

m_graphics.DrawString(strEncoded, fnt, txtBrush, new Point(200, 200), strFormatter);

é is encoded as U+00E9 in Unicode, which results in UTF-8 0xC3 0xA9 .

U+00C3 is à , and U+00A9 is © ( source ).

So you clearly have an encoding problem, and the relevant code is not the one you posted, but the code that receives the string from the web request and passes it through the page (code-behind?) into your DLL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM