2011-02-23 73 views
6

我想知道如何为UILabel创建文字描边?有没有可能的方法? enter image description hereuilabel大纲或描边

谢谢你,

#import <Foundation/Foundation.h> 


@interface CustomLabel : UILabel { 

} 

@end 

#import "CustomLabel.h" 


@implementation CustomLabel 

- (void)drawTextInRect:(CGRect)rect { 

    CGSize shadowOffset = self.shadowOffset; 
    UIColor *textColor = self.textColor; 

    CGContextRef c = UIGraphicsGetCurrentContext(); 
    CGContextSetLineWidth(c, 22); 

    CGContextSetTextDrawingMode(c, kCGTextStroke); 
    self.textColor = [UIColor whiteColor]; 
    [super drawTextInRect:rect]; 

    CGContextSetTextDrawingMode(c, kCGTextFill); 
    self.textColor = textColor; 
    self.shadowOffset = CGSizeMake(0, 0); 
    [super drawTextInRect:rect]; 

    self.shadowOffset = shadowOffset; 
    //works fine with no warning 
} 

现在的问题是我如何使用这个子类有不同的viewcontrollers一个IBOutlet中的标签。是不是:

label = [[CustomLabel alloc] initWithFrame:CGRectMake(0, 0, 190, 190)]; 
+0

你为什么不尝试在Interface Builder中创建'label'并且建立连接以便你的应用程序完成最少的工作? – Lynn 2011-02-23 18:01:46

+0

谢谢:)我很困惑:D现在很好用 – Momi 2011-02-23 20:20:45

+0

谢谢!好想法!仍然需要参数化,如线宽,颜色等。 – Bogdan 2012-07-18 16:23:45

回答

3

这可能是有益的一些补充的是取决于字体和字符,增加:

CGContextSetLineJoin(c,kCGLineJoinRound); 

可以防止过大施加到太尖锐的字符的笔画的伪影。

0

这个实现有一个问题。用笔画绘制文本与绘制没有笔画的文本会产生“未经处理”结果的字体宽度略有不同。您可以通过在填充文本周围添加一个不可见的笔划来解决这个问题。

,就应该替换:

CGContextSetTextDrawingMode(c, kCGTextFill); 
self.textColor = textColor; 
self.shadowOffset = CGSizeMake(0, 0); 
[super drawTextInRect:rect]; 

有:

CGContextSetTextDrawingMode(context, kCGTextFillStroke); 
self.textColor = textColor; 
[[UIColor clearColor] setStroke]; // invisible stroke 
self.shadowOffset = CGSizeMake(0, 0); 
[super drawTextInRect:rect]; 

我不是100%肯定,如果这是实打实的,因为我不知道是否self.textColor = textColor;有同样的效果作为[textColor setFill],但你明白了。

披露:我是THLabel的开发人员。

我刚刚发布了一个UILabel子类,它允许在文本和其他效果中使用大纲。你可以在这里找到它:https://github.com/tobihagemann/THLabel