天天看點

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 = f;  
        green = f;  
        blue = f;  
        glowSize=f;  
    }  
    return self;  
}  

//重寫UILable類的drawTextInRect方法  
-(void) drawTextInRect: (CGRect)rect {  
    //定義陰影區域  
    CGSize textShadowOffest = CGSizeMake(, );  
    //定義RGB顔色值  
    float textColors[] = {red, green, blue, };  
    //擷取繪制上下文  
    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);  
}