给label的文字添加模糊效果的阴影

通常的添加阴影只能给label添加,但是不能给label的文字添加。这次就来说一下如何给文字添加阴影。废话不说,直接上代码吧,有问题或者更好的建议欢迎评论哦。其实一开始自己也是想写一个category的,但是发现不行,如果有谁有好办法,一定要告诉我哦,谢谢啦!

#import <UIKit/UIKit.h>

@interface BorderTextLabel : UILabel

/** 描边宽度*/

@property (nonatomic, assign) CGFloat textBorderWidth;

/** 描边颜色*/

@property (nonatomic, strong) UIColor *textBorderColor;

/** 带阴影的文字*/

@property (nonatomic, strong) NSString *shadowText;

@end
#import "BorderTextLabel.h"

@implementation BorderTextLabel

@synthesize textBorderWidth = _textBorderWidth, textBorderColor = _textBorderColor, shadowText = _shadowText;

- (void)drawTextInRect:(CGRect)rect {

    UIColor *textColor = self.textColor;
    
    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(c, self.textBorderWidth);
    CGContextSetLineJoin(c, kCGLineJoinRound);
    
    CGContextSetTextDrawingMode(c, kCGTextStroke);
    self.textColor = self.textBorderColor;
    [super drawTextInRect:rect];
    
    CGContextSetTextDrawingMode(c, kCGTextFill);
    self.textColor = textColor;
    self.shadowOffset = CGSizeMake(0, 0);
    [super drawTextInRect:rect];
}

-(void)setShadowText:(NSString *)shadowText {
    _shadowText = shadowText;
    NSShadow *shadow = [[NSShadow alloc] init];
    shadow.shadowBlurRadius = 1.5;
    shadow.shadowOffset = CGSizeMake(0, 0);
    shadow.shadowColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
    NSAttributedString *attributedStr = [[NSAttributedString alloc] initWithString:shadowText
                                                                        attributes:@{NSShadowAttributeName:shadow}];
    self.attributedText = attributedStr;
}

@end

synthesize一定要写,否则不生效哦。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,241评论 4 61
  • 《没有记忆的人》 文/白传英 总想和你在一起 回到过去 你在我心里 变得不再珍惜 想知道你的过去 过去里有...
    白清风阅读 237评论 0 1
  • 首先要说的是,很久没有写东西了,一是这段时间有点忙,一直在忙着一件自己想了很久的事情,终于付之行动,刚一开始,还有...
    牛小妞阅读 392评论 0 0