从汉字中提取CGPathRef

时间:2012-08-27 16:36:11

标签: text core-graphics

我想得到一个汉字(日语)字符的轮廓。

以下代码适用于拉丁字符:

[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是一个正方形。我需要提取汉字的轮廓?

1 个答案:

答案 0 :(得分: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);