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

标签 ios objective-c iphone cocoa-touch core-graphics

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

我使用下面的代码对 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;

}

关于ios - 如何让 UILabel 显示带轮廓的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6598505/

相关文章:

ios - 如何仅在条件为真时执行 segue

iphone - 在 UIViewController 之间传递数据时获取 (null)

iphone - 使用 AFHTTPClient 设置非默认 HTTP header

ios - 在 Swift 中使用自定义点注释时出现错误

ios - UIButton 图像的最大缩放比例?

ios - Firebase 不会报告 iOS 中的所有崩溃,而 Xcode 10 会报告所有这些崩溃,我们能否以某种方式在 firebase 上跟踪所有这些崩溃?

ios - 添加到测试目标时的 IB 可设计错误

iphone - 在一个上下文中保留项目,但核心数据无法在另一上下文中找到项目?

objective-c - 用 cocoa 增加苹果标志的亮度?

iphone - 检查 NSMutableArray 中是否存在某些内容