【问题标题】:uilabel with outline or stroke [duplicate]带有轮廓或笔划的uilabel [重复]
【发布时间】:2011-07-02 21:05:02
【问题描述】:

我想知道如何为 UILabel 创建文本笔划?有什么可能的方法吗?

谢谢你,

#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 
}   

现在的问题是我如何在不同的视图控制器上使用这个带有 IBOutlet 标签的子类。对吗:

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

【问题讨论】:

  • 您为什么不尝试在 Interface Builder 中创建 label 并建立连接,以便您的应用完成最少的工作量?
  • 谢谢 :) 我很困惑 :D 现在效果很好
  • 谢谢!好点子!仍然需要参数化,比如线宽、颜色等。

标签: ios4 uilabel iphone


【解决方案1】:

此实现存在一个问题。绘制带笔划的文本与绘制不带笔划的文本相比,字符字形宽度略有不同,这会产生“未居中”的结果。您可以通过在填充文本周围添加不​​可见的笔划来解决此问题。

你应该替换:

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

【讨论】:

    【解决方案2】:

    根据字体和字符添加对某些人可能会有所帮助,添加:

    CGContextSetLineJoin(c,kCGLineJoinRound);
    

    可以防止过大的笔划应用于过于锐利的字符。

    【讨论】:

      猜你喜欢
      • 2018-12-11
      • 2020-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-30
      • 1970-01-01
      相关资源
      最近更新 更多