@interface CustomerLable : UILabel {
NSMutableAttributedString *mutaString;
}
@property (nonatomic,retain) NSMutableAttributedString *mutaString;
- (NSAttributedString *)illuminatedString:(NSString *)text font:(UIFont *)AtFont;
@end
//
// CustomerLable.m
// NSAttributeStr
//
// Created by wgd on 12-4-23.
// Copyright 2012 __MyCompanyName__. All rights reserved.
//
#import "CustomerLable.h"
@implementation CustomerLable
@synthesize mutaString;
- (NSAttributedString *)illuminatedString:(NSString *)text
font:(UIFont *)AtFont{
mutaString = [[[NSMutableAttributedString alloc] initWithString:@"adsfasfdadfadfas"] autorelease];
if(!mutaString)
{
self.mutaString = [[NSMutableAttributedString alloc] init];
[mutaString release];
}
CTFontRef font_hello = CTFontCreateWithName((CFStringRef)@"Helvetica",16,NULL);
CTFontRef font_world = CTFontCreateWithName((CFStringRef)@"GillSans",20,NULL);
[self.mutaString addAttribute:kCTFontAttributeName value:font_hello range:NSMakeRange(0, 3)];
[self.mutaString addAttribute:kCTFontAttributeName value:font_world range:NSMakeRange(0, 3)];
[self.mutaString addAttribute:(NSString *)(kCTForegroundColorAttributeName)
value:(id)[UIColor redColor].CGColor
range:NSMakeRange(0, 3)]; //放用戶名的長度+1
[self.mutaString addAttribute:(NSString *)(kCTForegroundColorAttributeName)
value:(id)[UIColor grayColor].CGColor
range:NSMakeRange(3, 2)];
return mutaString;
}
//重繪Text
- (void)drawRect:(CGRect)rect
{
//獲取當前label的上下文以便於之後的繪畫,這個是一個離屏。
CGContextRef context = UIGraphicsGetCurrentContext();
//壓棧,壓入圖形狀態棧中.每個圖形上下文維護一個圖形狀態棧,並不是所有的當前繪畫環境的圖形狀態的元素都被保存。圖形狀態中不考慮當前路徑,所以不保存
//保存現在得上下文圖形狀態。不管後續對context上繪製什麼都不會影響真正得屏幕。
CGContextSaveGState(context);
//x,y軸方向移動
CGContextTranslateCTM(context, 0.0, 0.0);
//縮放x,y軸方向縮放,-1.0爲反向1.0倍,座標系轉換,沿x軸翻轉180度
// CGContextScaleCTM(context, 1, 100);
// CGContextScaleCTM(context, 1, -1);
CGContextScaleCTM(context, 1, -1);
CGContextTranslateCTM(context, 0.0, - ceill(self.bounds.size.height) + 8);
CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)mutaString);
//設置文字繪畫的起點座標。
CGContextSetTextPosition(context, 0.0, 0.0);
//在離屏上繪製line
CTLineDraw(line, context);
//將離屏上得內容覆蓋到屏幕。此處得做法很像windows繪製中的雙緩衝。
CGContextRestoreGState(context);
CFRelease(line);
}
-(void)dealloc
{
[mutaString release];
[super dealloc];
}
@end