问题
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