美文网首页iOS Developer
给label的文字添加模糊效果的阴影

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

作者: Fiona_L | 来源:发表于2017-06-26 17:43 被阅读606次

    通常的添加阴影只能给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一定要写,否则不生效哦。

    相关文章

      网友评论

        本文标题:给label的文字添加模糊效果的阴影

        本文链接:https://www.haomeiwen.com/subject/vbvccxtx.html