2012-08-27 17 views
1

我想要得到汉字(日文)字符的轮廓。从日文汉字中提取CGPathRef

下面的代码正在为拉丁字符:

[letter drawInRect:brect withAttributes:attributes]; 
[...] 
CGGlyph glyph; 
glyph = [font glyphWithName: letter]; 
CGPathRef glyphPath = CTFontCreatePathForGlyph((__bridge CTFontRef) font, glyph, NULL); 
CGPathAddPath(path0, &transform, glyphPath); 

letter是汉字,例如男,该字符被正确地绘制,但是CGPathRef是正方形。我需要什么来提取汉字的轮廓?

回答

3

glyphWithName方法:需要glyphName,而不是字符。对于简单的拉丁字符,glyphName与字符 - @“A”相同。据我所知,汉字没有名字,虽然平假名和片假名做。汉字太多了,许多字形都是同一个汉字的变体。

所以你必须用汉字使用不同的方法。这是一个适合我的例子。

// Convert a single character to a bezier path 
- (UIBezierPath *)bezierPathFromChar:(NSString *)aChar inFont:(CTFontRef)aFont { 
// Buffers 
unichar chars[1]; 
CGGlyph glyphs[1]; 

// Copy the character into a buffer  
chars[0] = [aChar characterAtIndex:0]; 

// Encode the glyph for the single character into another buffer 
CTFontGetGlyphsForCharacters(aFont, chars, glyphs, 1); 

// Get the single glyph 
CGGlyph aGlyph = glyphs[0]; 

// Find a reference to the Core Graphics path for the glyph 
CGPathRef glyphPath = CTFontCreatePathForGlyph(aFont, aGlyph, NULL); 

// Create a bezier path from the CG path 
UIBezierPath *glyphBezierPath = [UIBezierPath bezierPath]; 
[glyphBezierPath moveToPoint:CGPointZero]; 
[glyphBezierPath appendPath:[UIBezierPath bezierPathWithCGPath:glyphPath]]; 

CGPathRelease(glyphPath); 

return glyphBezierPath; 
} 

使用这样的:

NSString *theChar = @"男"; 

CTFontRef font = CTFontCreateWithName(CFSTR("HiraKakuProN-W6"), 114.0, NULL); 

UIBezierPath *glyphBezierPath = [self bezierPathFromChar:theChar inFont:font]; 

编辑 - 定义可以定位的字体的另一种方式:

CTFontRef font = CTFontCreateWithName((CFStringRef)@"Helvetica-Bold", 114.0, NULL);