[英]subclass UILabel to have letter spacing doesn't work with accent letter
我在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是空的,我該如何解決這個問題?
加載字體時,您可能使用了錯誤的編碼。 嘗試更改此行:
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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.