CoreText实现图文混排和点击事件(2)
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithObject:(id)style forKey:(id)kCTParagraphStyleAttributeName ];
[content addAttributes:attributes range:NSMakeRange(0, [content length])];
//这里对需要进行点击事件的字符heightlight效果,这里简化解析过程,直接hard code需要heightlight的范围
[content addAttribute:(id)kCTForegroundColorAttributeName value:(id)[[UIColor blueColor]CGColor] range:NSMakeRange(0, 10)];
}
//CTRun的回调,销毁内存的回调
void RunDelegateDeallocCallback( void* refCon ){
}
//CTRun的回调,获取高度
CGFloat RunDelegateGetAscentCallback( void *refCon ){
    NSString *imageName = (NSString *)refCon;
    return 30;//[UIImage imageNamed:imageName].size.height;
}
CGFloat RunDelegateGetDescentCallback(void *refCon){
    return 0;
}
//CTRun的回调,获取宽度
CGFloat RunDelegateGetWidthCallback(void *refCon){
    NSString *imageName = (NSString *)refCon;
    return 30;//[UIImage imageNamed:imageName].size.width;
}
- (void)drawRect:(CGRect)rect
{
    //设置NSMutableAttributedString的所有属性
    [self buildAttribute];
    NSLog(@"rect:%@",NSStringFromCGRect(rect));
    CGContextRef context = UIGraphicsGetCurrentContext();
    //设置context的ctm,用于适应core text的坐标体系
    CGContextSaveGState(context);
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    CGContextTranslateCTM(context, 0, rect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    //设置CTFramesetter
    CTFramesetterRef framesetter =  CTFramesetterCreateWithAttributedString((CFAttributedStringRef)content);
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, CGRectMake(0, 0, rect.size.width, rect.size.height));
    //创建CTFrame
    _frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, content.length), path, NULL);
    //把文字内容绘制出来
    CTFrameDraw(_frame, context);
    //获取画出来的内容的行数
    CFArrayRef lines = CTFrameGetLines(_frame);
    //获取每行的原点坐标
    CGPoint lineOrigins[CFArrayGetCount(lines)];
    CTFrameGetLineOrigins(_frame, CFRangeMake(0, 0), lineOrigins);
    NSLog(@"line count = %ld",CFArrayGetCount(lines));
    for (int i = 0; i < CFArrayGetCount(lines); i++) {
        CTLineRef line = CFArrayGetValueAtIndex(lines, i);
	
相关新闻>>
- 发表评论
- 
				
- 最新评论 进入详细评论页>>









![[iPhone中级]iPhone团购信息客户端的开发 (二)](/uploads/allimg/131022/200H11235-0-lp.png)
