UILabel設置字體發光效果

1、新建一個繼承自UILabel的類
2、在這個類中定義red、green、blue三個顏色值變量和一個發光範圍變量glowSize。
3、重寫UILable的drawTextInRect方法,並使用CGContextRef來進行繪製。

.h文件

@interface FBGlowLabel : UILabel  

//定義顏色值全局變量和放大值全局變量  
@property(assign ,nonatomic) float red;  
@property(assign ,nonatomic) float green;  
@property(assign ,nonatomic) float blue;  
@property(assign ,nonatomic) float glowSize;  

.m文件

@implementation FBGlowLabel  
-(id) initWithFrame: (CGRect)frame {  
    if ((self = [super initWithFrame:frame])) {  
        //初始化  
        red = 0.0f;  
        green = 0.50f;  
        blue = 1.0f;  
        glowSize=40.0f;  
    }  
    return self;  
}  

//重寫UILable類的drawTextInRect方法  
-(void) drawTextInRect: (CGRect)rect {  
    //定義陰影區域  
    CGSize textShadowOffest = CGSizeMake(0, 0);  
    //定義RGB顏色值  
    float textColors[] = {red, green, blue, 1.0};  
    //獲取繪製上下文  
    CGContextRef ctx = UIGraphicsGetCurrentContext();  
    //保存上下文狀態  
    CGContextSaveGState(ctx);  
    //爲上下文設置陰影  
    CGContextSetShadow(ctx, textShadowOffest, glowSize);  
    //設置顏色類型  
    CGColorSpaceRef textColorSpace = CGColorSpaceCreateDeviceRGB();  
    //根據顏色類型和顏色值創建CGColorRef顏色  
    CGColorRef textColor = CGColorCreate(textColorSpace, textColors);  
    //爲上下文陰影設置顏色,陰影顏色,陰影大小  
    CGContextSetShadowWithColor(ctx, textShadowOffest, size, textColor);  

    [super drawTextInRect:rect];  

    //釋放  
    CGColorRelease(textColor);  
    CGColorSpaceRelease(textColorSpace);  

    //重啓上下文  
    CGContextRestoreGState(ctx);  
}  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章