UILabel描边效果

31 篇文章 0 订阅
7 篇文章 0 订阅

例子一:

转自: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.csdn.net/u010130947/article/details/51801888



可以达到文字描一圈黑边的效果


继承UILabel以后重载drawTextInRect

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. - (void)drawTextInRect:(CGRect)rect {  
  2.   
  3.    CGSize shadowOffset = self.shadowOffset;  
  4.    UIColor *textColor = self.textColor;  
  5.   
  6.    CGContextRef c = UIGraphicsGetCurrentContext();  
  7.    CGContextSetLineWidth(c, 1);  
  8.    CGContextSetLineJoin(c, kCGLineJoinRound);  
  9.   
  10.    CGContextSetTextDrawingMode(c, kCGTextStroke);  
  11.    self.textColor = [UIColor whiteColor];  
  12.    [super drawTextInRect:rect];  
  13.   
  14.    CGContextSetTextDrawingMode(c, kCGTextFill);  
  15.    self.textColor = textColor;  
  16.    self.shadowOffset = CGSizeMake(00);  
  17.    [super drawTextInRect:rect];  
  18.   
  19.    self.shadowOffset = shadowOffset;  
  20.   
  21. }  



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值