在iphone中编程显示中文
这个问题苦恼了我一个上午,现在总算弄明白了,现在开个贴总结一下,以慰来者。
先看代码:
/**********************code quoted begin*************************/
....
#import <UIKit/NSString-UIStringDrawing.h>
#import <GraphicsServices/GraphicsServices.h>
extern struct __GSFont * GSFontCreateWithName(char *name, int traits, float size);
-(void) testForDrawChineseChar:(CGRect) rc
{
/*获取当前的context*/
CGContextRef context;
context = UICurrentContext();
if ( context == nil ) return;
/*填充蓝色背景*/
CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0);
CGContextFillRect(context, rect);
/*设置字体填充颜色*/
CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 0.8);
/*struct __GSFont *fonts = [NSClassFromString(@"WebFontCache") createFontWithFamily:@"STHeiti" traits:2 size:16]; */
/*获取字体instance*/
struct __GSFont * fonts=GSFontCreateWithName(@"STHeiti", 1,18);
CGContextSetFont(context, fonts);
CGContextSetFontSize(context,18);
/*NSString *unicode = [NSString stringWithUTF8String: @"中文"];*/
/*初始化文字:中文二字*/
NSString *unicode=[NSString stringWithFormat:@"%C%C in Unicode", 0x4e2d,0x6587];
/*在200,200的x,y值画中文*/
[unicode drawAtPoint:CGPointMake(200.0,200.0) withFont: fonts];
return;
}
/**********************code quoted end***************************/
以下为过程中遇到的问题,首先我不得不承认,我还是个newbie,接触objective-c,3天左右,toolchain大概2天,所以遇到的问题要是幼稚点,希望各位能给我指出。
在mac中一般显示文字使用的是CGContextSelectFont,CGContextShowText,但是经过测试并且google了一下,CGContextShowText不支持unicode,所以只好另辟渠道,本站有人发帖使用GSFontCreateWithName创建字体,但不知为何在我的GraphicsServices.h中没有定义,只好手工写了一个extern,在洋人网站上屡屡提到的WebFontCache,经过我测试也不能够正确显示中文。
第二个问题是中文的存储,至少在cygwin环境下,使用[NSString stringWithFormat:@"%s", @"中文"];这种方式是不行的,只能够将中文转化成为二进制然后使用%c并format到NSString中才能正常使用,如果做过wap,对这个应该比较熟悉。
第三个问题是drawAtPoint或者drawAtRect,起始阶段我没有import NSString-UIStringDrawing,没想到drawxxxx是使用category实现,奇怪的是编译没有显示问题,运行的时候selector定位不到函数,这个地方想了我2个小时,玩惯了c/c++的主看来也要好好学习一下obj-c的语法了。
最后一个问题,希望哪位老大给我解释一下,为何我的toolchain中的.h里很多函数没有定义?是不是要把1.1.x的header引进来?我把1.1.2的header覆盖了我现在include,但是编译问题一堆,应该怎样才能升级header file呢?
另有兄弟提出使用resource file来解决,如果是对静态文字进行显示,亦可考虑使用NSLocalizedString,这个我研究不深,就不在妄言了。
-ddk
[ 本帖最后由 confused_ddk 于 2008-4-18 23:50 编辑 ]