我想要的只是白色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”顺从于我。