要使 UILabel 呈现为大写字符串,其中每个单词的第一个字母较大,您可以执行以下操作:
@implementation CapitalicTextLabel
- (void)drawRect:(CGRect)rect
{
// Drawing code
NSArray* words = [self.text componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetCharacterSpacing(context, 1);
CGContextSetFillColorWithColor(context, [self.textColor CGColor]);
CGAffineTransform myTextTransform = CGAffineTransformScale(CGAffineTransformIdentity, 1.f, -1.f );
CGContextSetTextMatrix (context, myTextTransform);
CGFloat x = 0;
float centeredY = (self.font.pointSize + (self.frame.size.height - self.font.pointSize) / 2) - 2;
CGFloat firstLetterSize = self.font.pointSize * 1.4;
for (NSString* word in words)
{
NSString* letter = [[word substringToIndex:1] uppercaseString];
CGContextSelectFont(context, [self.font.fontName cStringUsingEncoding:NSASCIIStringEncoding], firstLetterSize, kCGEncodingMacRoman);
CGContextShowTextAtPoint(context, x, centeredY, [letter cStringUsingEncoding:NSASCIIStringEncoding], [letter length]);
x = CGContextGetTextPosition(context).x;
NSString* restOfWord = [[[word substringFromIndex:1] uppercaseString] stringByAppendingString:@" "];
CGContextSelectFont(context, [self.font.fontName cStringUsingEncoding:NSASCIIStringEncoding], self.font.pointSize,
kCGEncodingMacRoman);
CGContextShowTextAtPoint(context, x, centeredY, [restOfWord cStringUsingEncoding:NSASCIIStringEncoding], [restOfWord length]);
CGPoint v = CGContextGetTextPosition(context);
x = CGContextGetTextPosition(context).x;
}
}
@end
此实现不处理跨多行的拆分或遵守 TextAlignment 设置,这应该足够简单,以便以后添加。
例子: