unicode symbols printing with ¬ before ° sign when printed using CGContextShowTextAtPoint

此生再无相见时 提交于 2019-12-24 13:27:34

问题


I am printing a ° or a µ on my view using the CGContextShowTextAtPoint call. the line of code is as shown.

int number = 100;
NSString *theText2 = [NSString stringWithFormat:@"%d°", number];
CGContextShowTextAtPoint(context, 10, 5, [theText2 cStringUsingEncoding:NSUTF8StringEncoding], [theText2 length]);

The output of this comes out as

"100¬"

If I increase the length of the string printed it shows the following

"100¬°"

The expected output should be:

"100°"

This surely has to do something with printing unicode characters.


回答1:


For CGContextShowTextAtPoint you have to convert the string to the encoding that was specified in CGContextSelectFont. Most probably this is the "Mac Roman" encoding. And the last argument of CGContextShowTextAtPoint is the length of the converted string, not the length of the NSString:

CGContextSelectFont(context, "Helvetica", 10.0, kCGEncodingMacRoman);

int number = 100;
NSString *theText2 = [NSString stringWithFormat:@"%d°µ", number];
const char *s = [theText2 cStringUsingEncoding:NSMacOSRomanStringEncoding];
CGContextShowTextAtPoint(context, 10, 5, s, strlen(s));

Note that this works only as long as you use characters from the "Mac Roman" character set. (And it does also not work for the Euro character due to some historical changes in the Mac Roman encoding.)

For general Unicode strings the NSString method drawAtPoint:withFont: might be better suited.




回答2:


I know it has some Encoding problem. But here is a small fix Use this where 161 represent the degree symbol

char str[20] = {0};
sprintf(str, "%d%c",number,161);
CGContextShowTextAtPoint(context, 10, 5, str, strlen(str));


来源:https://stackoverflow.com/questions/13738158/unicode-symbols-printing-with-%c2%ac-before-sign-when-printed-using-cgcontextshowte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!