我想要的只是白色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",但是我似乎根本不能让draTextInRect屈从于我的意愿,尽管我全神贯注地盯着它,皱着眉头,真的真的很难.

推荐答案

我可以通过重写draTextInRect来完成此操作:

- (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相关问答推荐

Swift:从字符串目录获取带有参数的本地化字符串

无法在fastlane和github操作中从react-native 应用程序构建ios

Fastlane,iOS Provisioning Profile推送通知权限(通过示例)&

许多文本字段的性能问题

安装新版本 XCode 15.0 后无法运行应用程序 XCode

发生错误.请稍后重试.在 App Store 连接中

仅更改 AttributedString 的字符串(例如 UIButton 配置 attributeTitle)

保存和读取登录到 keys 串不工作 IOS swift

如何在SwiftUI中实现淡入淡出加粘标题屏幕效果

尽管存在浮点错误,如何显示正确的计算结果.计算器应用程序

部分保留 UITextField 中的占位符

React Native IOS base64 编码图像不显示

iOS 如何使用 Alamofire 解析 JSON 可编码数组

将 SwiftUI 与 @AppStorage 和动态函数调用一起使用

Got Unrecognized selector -replacementObjectForKeyedArchiver: 在 Swift 中实现 NSCoding 时崩溃

iOS:使用 UIView 的 'drawRect:' 与其层的委托 'drawLayer:inContext:'

SRCROOT 和 PROJECT_DIR 有什么区别?

如何删除 Swift 数组中的所有 nil 元素?

如何找到 UILabel 的实际行数?

从 Swift 转换为 Objective-c 的工具