我想拉伸UILabel中的文本,以便如果完全符合標籤(寬度和高度)。我不想以任何方式調整UILabel的大小。如何根據標籤大小調整文本大小?
到目前爲止,我使用這個:How to render stretched text in iOS?,但文本不能伸展100%(有時它超出了邊界,有時它留下邊距的間距)。
是否有另一種(最好更容易)的方法來做到這一點?我想說的是:http://i.imgur.com/AMvfhsA.png。我在左側獲得間距,文本超出右側和底部邊界的邊界。
這是自定義標籤類:
#import "CustomUILabel.h"
@implementation CustomUILabel
- (id)initWithFrame:(CGRect)frame text:(NSString*)text
{
self = [super initWithFrame:frame];
if (self) {
self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
self.text = text;
}
return self;
}
- (void)drawTextInRect:(CGRect)rect {
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
}
- (void)drawRect:(CGRect)rect
{
[self drawScaledString:self.text];
}
- (void)drawScaledString:(NSString *)string
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
NSAttributedString *attrString = [self generateAttributedString:string];
CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attrString, CFRangeMake(0, string.length),
kCTForegroundColorAttributeName, self.textColor.CGColor);
CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef) attrString);
// CTLineGetTypographicBounds doesn't give correct values,
// using GetImageBounds instead
CGRect imageBounds = CTLineGetImageBounds(line, context);
CGFloat width = imageBounds.size.width;
CGFloat height = imageBounds.size.height;
CGFloat padding = 0;
width += padding;
height += padding;
float sx = self.bounds.size.width/width;
float sy = self.bounds.size.height/height;
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 1, self.bounds.size.height);
CGContextScaleCTM(context, 1, -1);
CGContextScaleCTM(context, sx, sy);
CGContextSetTextPosition(context, -imageBounds.origin.x + padding/2, -imageBounds.origin.y + padding/2);
CTLineDraw(line, context);
CFRelease(line);
}
- (NSAttributedString *)generateAttributedString:(NSString *)string
{
CTFontRef helv = CTFontCreateWithName(CFSTR("Helvetica-Bold"),20, NULL);
CGColorRef color = [UIColor blackColor].CGColor;
NSDictionary *attributesDict = [NSDictionary dictionaryWithObjectsAndKeys:
(__bridge id)helv, (NSString *)kCTFontAttributeName,
color, (NSString *)kCTForegroundColorAttributeName,
nil];
NSAttributedString *attrString = [[NSMutableAttributedString alloc]
initWithString:string
attributes:attributesDict];
return attrString;
}
@end
這也是我如何使用它(我已經添加了從故事板標籤):
@property (weak, nonatomic) IBOutlet CustomUILabel *label;
...
self.label.backgroundColor = [UIColor redColor];
self.label.text = @"OOOOO";
你的意思是你想要真正拉伸文本或你想要適應字體大小取決於標籤大小? – Vik
另一個問題在理論上是合理的,所以它表明你有一些計算錯誤。顯示您針對指定輸入顯示的問題的代碼和屏幕截圖。 – Wain
我真的很想拉伸文本。 – meee