http://blog.csdn.net/xcysuccess3 版权所有 ,转载请说明
这三天自己一直在研究如何绘制文字,首先是找了CoreText, 但是没有发现DrawAtPosition的方法,无奈之下转向CoreGraphic,这里倒是有一个DrawAtPosition,具体思路就是把文字转换成图元然后去绘制。这位仁兄讲的非常好:http://blog.csdn.net/kmyhy/article/details/7651794
大家可以去参考。他还提供了源码。
但是使用Coretext如何按照坐标进行自由绘制呢?当然,CoreText内置了文字排版,但是这个有些并不精确。翻遍了API,并无发现DrawPosition方法.难道真的没办法了么?
答案是否定的。参考代码如下:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.backgroundColor =[UIColor clearColor];
}
return self;
}
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
CGMutablePathRef path = CGPathCreateMutable(); //1
// CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGPathAddRect(path, NULL, self.bounds );
for(int i = 0 ;i<3;++i)
{
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextSaveGState(context);
NSLog(@"self.bounds.size.height==>%f",self.bounds.size.height);
if(i==0)
{
CGContextTranslateCTM(context, 20 , self.bounds.size.height);
}
else if (i==1)
{
CGContextTranslateCTM(context, 20 , self.bounds.size.height+10);
}
else
{
CGContextTranslateCTM(context, 180 , self.bounds.size.height);
}
CGContextScaleCTM(context, 1.0, -1.0);
NSMutableAttributedString* attStringTemp = [[[NSMutableAttributedString alloc]
initWithString:@"hello coretext world!"]autorelease];
[attStringTemp addAttribute:(NSString*)(kCTForegroundColorAttributeName) value:(id)[[UIColor blueColor]CGColor] range:NSMakeRange(0,[attStringTemp length])];
CTFramesetterRef framesetter =
CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attStringTemp); //3
CTFrameRef frame =
CTFramesetterCreateFrame(framesetter,
CFRangeMake(0, 0), path, NULL);
CTFrameDraw(frame, context); //4
CGContextRestoreGState(context);
CFRelease(frame); //5
CFRelease(framesetter);
}
CFRelease(path);
}
这里利用坐标系进行坐标绘制,只需要一个UIView.并不会造成资源的过度浪费。这里要注意的就是坐标系的状态保存与恢复。
方法2:
coreText/Classes/PRPAttributedLabel.m
- (void)drawRect:(CGRect)rect {
if (self.attributedText == nil)
return;
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextTranslateCTM(context, self.bounds.size.width/2,
self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)
self.attributedText);
CGContextSetTextPosition(context, ceill(-self.bounds.size.width/2),
ceill(self.bounds.size.height/4));
CTLineDraw(line, context);
CGContextRestoreGState(context);
CFRelease(line);
}
方法二在竖排绘制的时候没有方法一方便。具体可参考 :http://blog.csdn.net/xcysuccess3/article/details/8102913
起点随笔
2012-10-22
ios交流QQ群:237305299