2010年8月15日 星期日

在UIView中用Custom Font畫中文/日文

由於轉了新公司,前2個月太多野做,沒有再更新BLOGER了
之前完成了一個電子書的項目,
發現原來要在iPhone SDK中的UIView也可以支持Custom Font去繪制文字
以下是代碼:

//載入字體
NSString *fontPath = [[NSBundle mainBundle] pathForResource:fontName ofType:@"ttf"];
CGDataProviderRef fontDataProvider = CGDataProviderCreateWithFilename([fontPath UTF8String]);
font = CGFontCreateWithDataProvider(fontDataProvider);
CGDataProviderRelease(fontDataProvider);

CGContextSetFont(ctx, font);
CGContextSetFontSize(ctx, fontSize);

在DrawRect Function下的繪制代碼
//把繪畫的Matrix上下倒轉
CGAffineTransform transform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0);
CGContextSetTextMatrix(ctx, transform);

//垂直繪畫文字
CGContextSetFillColorWithColor(ctx, fontColor.CGColor);
NSString *str = @"要繪畫的文字";
CGGlyph _glyphs[[str length]];
unichar _chars[[str length]];
for(int i = 0; i < [str length]; i++) _chars[i] = [str characterAtIndex:i]; //CGFontGetGlyphsForUnichars是私有API,在SDK 4.0中無法使用 //CGFontGetGlyphsForUnichars(_cgFont, _chars, _glyphs, [str length]); //CMFontGetGlyphsForUnichars是有一個開源的彷CGFontGetGlyphsForUnichars庫,不過也比私有API慢3倍時間 //CMFontGetGlyphsForUnichars download link: http://github.com/jamesjhu/CMGlyphDrawing5 CMFontGetGlyphsForUnichars(font, _chars, _glyphs, [str length]); //正式繪畫 CGContextShowGlyphsAtPoint(ctx, x, y, _glyphs, [str length]);



PS:其實SDK3.2開始UIFont已支持Custom Font,不過用SDK3.2支持Custom Font方法在IOS3.2以下是無法有效果的