ios - 如何让 UILabel 显示轮廓文本?

我想要的只是在我的白色 UILabel 文本周围有一个 1 像素的黑色边框。

我用下面的代码对 UILabel 进行了子类化,我从一些切线相关的在线示例中笨拙地拼凑起来。它可以工作,但是非常非常慢(在模拟器上除外),而且我也无法让它垂直居中文本(所以我暂时在最后一行硬编码了 y 值)。啊啊啊!

void ShowStringCentered(CGContextRef gc, float x, float y, const char *str) {
    CGContextSetTextDrawingMode(gc, kCGTextInvisible);
    CGContextShowTextAtPoint(gc, 0, 0, str, strlen(str));
    CGPoint pt = CGContextGetTextPosition(gc);

    CGContextSetTextDrawingMode(gc, kCGTextFillStroke);

    CGContextShowTextAtPoint(gc, x - pt.x / 2, y, str, strlen(str));
}


- (void)drawRect:(CGRect)rect{

    CGContextRef theContext = UIGraphicsGetCurrentContext();
    CGRect viewBounds = self.bounds;

    CGContextTranslateCTM(theContext, 0, viewBounds.size.height);
    CGContextScaleCTM(theContext, 1, -1);

    CGContextSelectFont (theContext, "Helvetica", viewBounds.size.height,  kCGEncodingMacRoman);

    CGContextSetRGBFillColor (theContext, 1, 1, 1, 1);
    CGContextSetRGBStrokeColor (theContext, 0, 0, 0, 1);
    CGContextSetLineWidth(theContext, 1.0);

    ShowStringCentered(theContext, rect.size.width / 2.0, 12, [[self text] cStringUsingEncoding:NSASCIIStringEncoding]);
}

我只是有一种唠叨的感觉,我忽略了一种更简单的方法来做到这一点。也许是通过覆盖“drawTextInRect”,但我似乎根本无法让 drawTextInRect 屈服于我的意愿,尽管我专心地盯着它,皱着眉头。

最佳答案

我可以通过覆盖 drawTextInRect 来做到这一点:

- (void)drawTextInRect:(CGRect)rect {

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

  CGContextRef c = UIGraphicsGetCurrentContext();
  CGContextSetLineWidth(c, 1);
  CGContextSetLineJoin(c, kCGLineJoinRound);

  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;

}

https://stackoverflow.com/questions/1103148/

相关文章:

iphone - 我在 iPhone 上的日期字符串中使用什么格式的字符串来表示毫秒?

objective-c - 如何将 int 转换为 NSString?

ios - UIAlertView 首先弃用 IOS 9

ios - 快速创建和播放声音

objective-c - NSString 带\n 或换行符

ios - 键盘出现时如何滚动 UIScrollView?

iphone - 即使图像较小,如何使 UITableViewCell 的 ImageView 成为

objective-c - libxml/tree.h 没有这样的文件或目录

iphone - 为 UIView 子类加载 Nib 的正确方法

ios - 如何检查 View Controller 是否以模态方式呈现或推送到导航堆栈上?