#import <CoreText/CoreText.h>
#import <QuartzCore/QuartzCore.h>
NSAttributedString *getAttributedString(){
NSMutableAttributedString *attriString = [[[NSMutableAttributedString
alloc] initWithString:@"this is test!"]
autorelease];
//把this的字型顏色變為紅色
[attriString addAttribute NSString *)kCTForegroundColorAttributeName
value id)[UIColor
redColor].CGColor
range:NSMakeRange(0,
4)];
//把is變為黃色
[attriString addAttribute NSString *)kCTForegroundColorAttributeName
value id)[UIColor
yellowColor].CGColor
range:NSMakeRange(5,
2)];
//改變this的字型,value必須是一個CTFontRef
[attriString addAttribute NSString *)kCTFontAttributeName
value id)CTFontCreateWithName((CFStringRef)[UIFont
boldSystemFontOfSize:14].fontName,
14,
NULL)
range:NSMakeRange(0,
4)];
//給this加上底線,value可以在指定的枚舉中選擇
[attriString addAttribute NSString *)kCTUnderlineStyleAttributeName
value id)[NSNumber
numberWithInt:kCTUnderlineStyleDouble]
range:NSMakeRange(0,
4)];
return attriString;
}
@interface TView : UIView
@end
@implementation TView
- (id)initWithFrame:(CGRect)frame
{
self = [super
initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor
clearColor];
}
return self;
}
-(void)drawRect:(CGRect)rect{
[super drawRect:rect];
NSAttributedString *attriString =
getAttributedString();
CGContextRef ctx =
UIGraphicsGetCurrentContext();
CGContextConcatCTM(ctx,
CGAffineTransformScale(CGAffineTransformMakeTranslation(0, rect.size.height),
1.f, -1.f));
// CGContextTranslateCTM(ctx, 0, rect.size.height);
// CGContextScaleCTM(ctx, 1, -1);
CTFramesetterRef framesetter =
CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attriString);
CGMutablePathRef path =
CGPathCreateMutable();
CGPathAddRect(path, NULL, rect);
CTFrameRef frame =
CTFramesetterCreateFrame(framesetter, CFRangeMake(0,
0), path, NULL);
CFRelease(path);
CFRelease(framesetter);
CTFrameDraw(frame, ctx);
CFRelease(frame);
}
@end
@interface BIDViewController ()
@end
@implementation BIDViewController
- (void)viewDidLoad
{
[super
viewDidLoad];
TView *view = [[TView
alloc] initWithFrame:CGRectMake(0,
0, 200, 200)];
[self.view
addSubview:view];
[view release];
CATextLayer *textLayer = [CATextLayer
layer];
textLayer.string = getAttributedString();
textLayer.frame = CGRectMake(0,
CGRectGetMaxY(view.frame),
200, 200);
[self.view.layer
addSublayer:textLayer];
}
- (void)viewDidUnload
{
[super
viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation !=
UIInterfaceOrientationPortraitUpsideDown);
}
@end
轉自 Created by zhangao on 5/30/12.