0

我在 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 是空的,我该如何解决这个问题?

4

1 回答 1

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.
于 2013-04-21T16:30:51.347 回答