子类UILabel有字母间距不适用于重音字母

时间:2013-04-21 16:21:47

标签: iphone ios uilabel uifont

我在SO上找到了这个代码,帮助我在UILabel中有一个字母间距,这是代码:

- (void) drawRect:(CGRect)rect
{
// Drawing code
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSelectFont (context, [self.font.fontName cStringUsingEncoding:NSASCIIStringEncoding], self.font.pointSize, kCGEncodingMacRoman);
CGContextSetCharacterSpacing(context, 2);
CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
CGAffineTransform myTextTransform = CGAffineTransformScale(CGAffineTransformIdentity, 1.f, -1.f );

CGContextSetTextMatrix (context, myTextTransform);

// draw 1 but invisbly to get the string length.
CGPoint p =CGContextGetTextPosition(context);
float centeredY = (self.font.pointSize + (self.frame.size.height- self.font.pointSize)/2)-2;
CGContextShowTextAtPoint(context, 0, centeredY, [self.text cStringUsingEncoding:NSASCIIStringEncoding], [self.text length]);
CGPoint v =CGContextGetTextPosition(context);

// calculate width and draw second one.
float width = v.x - p.x;
float destX = 0;

// calculate X position based on alignment
if([self textAlignment] == UITextAlignmentLeft){
    destX = 0;
}else if([self textAlignment] == UITextAlignmentCenter){
    destX = (self.frame.size.width- width)/2;
}else if([self textAlignment] == UITextAlignmentRight){
    destX = self.frame.size.width - width;
}
CGContextSetFillColorWithColor(context, [self.textColor CGColor]);
CGContextShowTextAtPoint(context, destX, centeredY, [self.text cStringUsingEncoding:NSASCIIStringEncoding], [self.text length]);
}

问题是,像èàòé这样的重音字母uilabel是空的,我怎么能解决这个问题?

1 个答案:

答案 0 :(得分:0)

加载字体时可能使用了错误的编码。尝试更改此行:

CGContextSelectFont (context, [self.font.fontName cStringUsingEncoding:NSASCIIStringEncoding], self.font.pointSize, kCGEncodingMacRoman);

改为使用此编码:

    CGContextSelectFont (context, [self.font.fontName cStringUsingEncoding:NSASCIIStringEncoding], self.font.pointSize, kCGEncodingFontSpecific);

然后在你输出字符串的地方使用这种编码NSASCIIStringEncoding,根据Apple文档,它绝对不包含你想要的字符。因此,即使您使用正确的编码读入字符集,也不会将其输出。

因为从Apple Docs编码您使用输出字符串:

 NSASCIIStringEncoding
 Strict 7-bit ASCII encoding within 8-bit chars; ASCII values 0…127 only.
 Available in iOS 2.0 and later.