2012-08-27 50 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);