例子一:
转自:http://www.tuicool.com/articles/ayAvArZ
产品让搞一个文字带描边的 Label 样式,长这个样子。
第一反应自然是使用 NSAttributedString
中的属性,查了一下果然有个 NSStrokeWidthAttributeName
和 NSStrokeColorAttributeName
。
但使用了之后效果完全和想象中的不一样。根据苹果文档 Technical Q&A QA1531 中的描述,使用之后确实有描边了,但只有一丢丢,而且非常坑爹的是,这样设置的描边是朝里的,也就是说 strokeWidth
设置得越大,文字的 fillColor
就越小。
由于这篇官方文档的标题和我的需求实在太符合了,导致我一直认为肯定是我用错了。一定有正确的方式来设置这个描边的宽度。
在折腾了一个多小时后,终于放弃了这个方案。最后在一篇 博客 中找到了正确使用方法——重写 drawTextInRect:
。
- (void)drawTextInRect:(CGRect)rect {
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(c, self.strokeWidth);
CGContextSetLineJoin(c, kCGLineJoinRound);
CGContextSetTextDrawingMode(c, kCGTextStroke);
self.textColor = self.strokeColor;
[super drawTextInRect:rect];
self.textColor = self.fillColor;
CGContextSetTextDrawingMode(c, kCGTextFill);
[super drawTextInRect:rect];
}
例子二:
转自:http://blog.youkuaiyun.com/u010130947/article/details/51801888
可以达到文字描一圈黑边的效果
继承UILabel以后重载drawTextInRect