我所需要的是一个像素的黑色边框围绕我的白色 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]);
}
我只是觉得自己忽略了一个更简单的方法。也许是通过覆盖“ dratTextInRect”,但我似乎无法让 dratTextInRect 屈服于我的意志,尽管我专注地盯着它,皱起眉头非常非常努力。