iOS 镂空文字效果

来源:互联网 发布:装修花费知乎 编辑:程序博客网 时间:2024/06/10 06:20

注意:一定要继承于UILabel,如果继承于UIView的话镂空的效果出不来


#import <UIKit/UIKit.h>


@interface HollowOutLabel : UILabel


@end

=============================================================

#import "HollowOutLabel.h"


@implementation HollowOutLabel

{

    NSString * _text;

    UIFont * _font;

    UIColor * _backgroundColor;

    CGRect _frame;

}


#pragma mark - 重写对应的set方法

- (void)setText:(NSString *)text

{

    _text = text;

}


- (void)setFont:(UIFont *)font

{

    _font = font;

}


- (void)setBackgroundColor:(UIColor *)backgroundColor

{

    _backgroundColor = backgroundColor;

}


//这个方法会出问题,因而重写置空

- (void)sizeToFit

{

    

}


- (instancetype)init//禁止使用此方法初始化

{

    returnnil;

}


- (instancetype)initWithFrame:(CGRect)frame

{

    if (self = [superinitWithFrame:frame]) {

        _frame = frame;

    }

    returnself;

}


#pragma mark - 绘制

- (void)drawRect:(CGRect)rect

{

    CGContextRef context =UIGraphicsGetCurrentContext();

    

    [selfdrawSubtractedText:_textinRect:_frameinContext:context];

}


- (void)drawSubtractedText:(NSString *)text inRect:(CGRect)rect inContext:(CGContextRef)context

{

    //将当前图形状态推入堆栈

    CGContextSaveGState(context);

    

    //设置混合色

    CGContextSetBlendMode(context,kCGBlendModeDestinationOut);

    

    //label上面添加label

    UILabel *label = [[UILabelalloc] initWithFrame:rect];

    label.font =_font;

    label.text = text;

    label.textAlignment =NSTextAlignmentCenter;

    label.backgroundColor =_backgroundColor;

    

    [label.layerdrawInContext:context];

    

    //把堆栈顶部的状态弹出,返回到之前的图形状态

    CGContextRestoreGState(context);

}



@end



0 0