两种方式 创建富文本的代码 ios +

#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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值