iOS中 图文混排/自定义图文混排

指示根视图:(准备几张图片,把label加载在window上)

[objc]  view plain  copy
  1. CustomLable *label =  [[CustomLable alloc]initWithFrame:CGRectMake(060self.window.bounds.size.widthself.window.bounds.size.height)];  
  2.   label.backgroundColor = [UIColor greenColor];  
  3.   [self.window addSubview:label];  

引进框架:

#import <CoreText/CoreText.h>

建一个类,继承自UILabel

返回图片的高:

[objc]  view plain  copy
  1. // 返回图片的高  
  2. CGFloat runDelegateGetAscentCallback(voidvoid *refcon) {  
  3.       
  4.     NSString *imageName = (__bridge NSString *)refcon;  
  5.     return [UIImage imageNamed:imageName].size.height;  
  6.       
  7.       
  8. }  
返回图片的宽:
[objc]  view plain  copy
  1. // 返回图片的宽  
  2. CGFloat runDelegateGetWidthCallback(voidvoid *refcon) {  
  3. //    NSString *imageName = (__bridge NSString *)refcon;  
  4.     // 让绘制图片的宽度为屏幕的宽, 使文本中只要遇到图片就换行(配合上面的换行模式)  
  5.     // 如果不想换行可以直接返回图片的宽  
  6.       
  7.     return [UIScreen mainScreen].bounds.size.width;  
  8.       
  9. }  
[objc]  view plain  copy
  1. CGFloat runDelegateGetDescentCallback(voidvoid *refcon){  
  2.     return 0;  
  3. }  


开始绘制及相关计算:

[objc]  view plain  copy
  1. #import "CustomLable.h"  
  2. #import <CoreText/CoreText.h>  
  3. @implementation CustomLable  
  4.   
  5. - (void)drawRect:(CGRect)rect  
  6. {  
  7.     [super drawRect:rect];  
  8.       
  9.     // 创建绘制区域  
  10.     CGMutablePathRef path = CGPathCreateMutable();  
  11.     CGPathAddRect(path, nil, CGRectMake(00self.bounds.size.widthself.bounds.size.height));  
  12.       
  13.     // 获取当前用于绘制画布的上下文, 用于后续将内容绘制到画布上  
  14.     CGContextRef context = UIGraphicsGetCurrentContext();  
  15.       
  16.     // 翻转坐标系  
  17.     // 参数1:文本宽度占Label的比例(0 ~ 1)  
  18.     // 参数2:水平方向文字逐渐往下(参数 > 0, 往上: 参数 < 0)偏移,如果是正数,逐渐向上偏移  
  19.     // 参数3:在竖直方向上,从下往上每行文字逐渐往右(参数 > 0, 往左: 参数 < 0)偏移  
  20.     // 参数4:文本首行的纵坐标占Label的比例(-1 ~ 0)  
  21.     // 参数5:文本整体往右(参数 > 0, 往左: 参数 < 0)偏移量  
  22.     // 参数6:文本整体在纵坐标方向的偏移量,参数 > label的高度, 往下偏移, 参数 < label的高度, 往上偏移  
  23.     CGContextConcatCTM(context, CGAffineTransformMake(100, -10self.bounds.size.height));  
  24.       
  25.     // 准备文本  
  26.     NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc]initWithString:@"iOS程序在启动时会创建一个主线程,而在一个线程只能执行一件事情,如果在主线程执行某些耗时操作,例如加载网络图片,下载资源文件等会阻塞主线程(导致界面卡死,无法交互),所以就需要使用多线程技术来避免这类情况。iOS中有三种多线程技术 NSThread,NSOperation,GCD,这三种技术是随着IOS发展引入的,抽象层次由低到高,使用也越来越简单。"];  
  27.       
  28.     // 改变字体大小  
  29.     [attrString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:24] range:NSMakeRange(05)];  
  30.       
  31.     // 改变字体颜色  
  32.     [attrString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(05)];  
  33.        
  34.        
  35.       
  36.     // 换行模式 (当Label的宽度不够显示内容或图片的时候就自动换行) (默认状态下如果不够显示图片, 不会自动换行, 部分图片就会看不见)  
  37.     CTParagraphStyleSetting lineBreakMode;  
  38.     CTLineBreakMode lineBreak = kCTLineBreakByCharWrapping;  
  39.     lineBreakMode.spec = kCTParagraphStyleSpecifierLineBreakMode;  
  40.     lineBreakMode.value = &lineBreak;  
  41.     lineBreakMode.valueSize = sizeof(CTLineBreakMode);  
  42.     CTParagraphStyleSetting setting[] = {lineBreakMode};  
  43.     CTParagraphStyleRef style = CTParagraphStyleCreate(setting, 1);  
  44.     NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithObject:(__bridge id)style forKey:(id)kCTParagraphStyleAttributeName];  
  45.     [attrString addAttributes:attributes range:NSMakeRange(0, attrString.length)];  
  46.       
  47.     // 设置CTRunDelegateCallbacks 获取图片大小  
  48.     CTRunDelegateCallbacks imageCallbacks;  
  49.     imageCallbacks.version = kCTRunDelegateVersion1;  
  50.       
  51.     // 获取图片的高 (可自由设置返回的高)  
  52.     imageCallbacks.getAscent = runDelegateGetAscentCallback;  
  53.       
  54.     // 设置图片下一行文字距离图片的距离  
  55.     imageCallbacks.getDescent = runDelegateGetDescentCallback;  
  56.       
  57.     // 获取图片的宽 (可自由设置返回宽度)  
  58.     imageCallbacks.getWidth = runDelegateGetWidthCallback;  
  59.       
  60.     // 空格用于给图片留个位置  
  61.     NSMutableAttributedString *imageAttributedString = [[NSMutableAttributedString alloc]initWithString:@" "];  
  62.       
  63.     // 根据图片占用尺寸的大小给图片留位置显示  
  64.     CTRunDelegateRef runDelegate = CTRunDelegateCreate(&imageCallbacks, (__bridge voidvoid *)(@"Untitled.png"));  
  65.   
  66.     [imageAttributedString addAttribute:(NSString *)kCTRunDelegateAttributeName value:(__bridge id)runDelegate range:NSMakeRange(01)];  
  67.       
  68.     // 将图片显示在指定位置  
  69.     NSString *imageKey = @"imageName";  
  70.     [imageAttributedString addAttribute:imageKey value:@"Untitled.png" range:NSMakeRange(01)];  
  71.      
  72.       
  73.     // 设置插入图片的位置  
  74.     [attrString insertAttributedString:imageAttributedString atIndex:38];  
  75.       
  76.       
  77.     //根据NSMutableAttributedString生成frame  
  78.     CTFrameRef frame = CTFramesetterCreateFrame(CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attrString), CFRangeMake(0, attrString.length), path, nil);  
  79.       
  80.     // 开始绘制  
  81.     CTFrameDraw(frame, context);  
  82.       
  83.     CFArrayRef lines = CTFrameGetLines(frame);  
  84.     CGPoint lineOrigins[CFArrayGetCount(lines)];  
  85.     CTFrameGetLineOrigins(frame, CFRangeMake(00), lineOrigins);  
  86.     for (int i = 0; i < CFArrayGetCount(lines); i++) {  
  87.         CTLineRef line = CFArrayGetValueAtIndex(lines, i);  
  88.         CFArrayRef runs = CTLineGetGlyphRuns(line);  
  89.         for (int j = 0; j < CFArrayGetCount(runs); j++) {  
  90.             CGFloat runAscent;  
  91.             CGFloat runDescent;  
  92.             CGPoint lineOrigin = lineOrigins[i];  
  93.             CTRunRef run = CFArrayGetValueAtIndex(runs, j);  
  94.             NSDictionary *mAttrinbutes = (NSDictionary *)CTRunGetAttributes(run);  
  95.             CGRect runRect;  
  96.             runRect.size.width = CTRunGetTypographicBounds(run, CFRangeMake(00), &runAscent, &runDescent, NULL);  
  97.             runRect = CGRectMake(lineOrigin.x + CTLineGetOffsetForStringIndex(line, CTRunGetStringRange(run).locationNULL), lineOrigin.y - runDescent, runRect.size.width, runAscent + runDescent);  
  98.   
  99.             NSString *imageName = [mAttrinbutes objectForKey:imageKey];  
  100.             // 图片的渲染逻辑  
  101.             if (imageName) {  
  102.                 UIImage *image = [UIImage imageNamed:imageName];  
  103.                 CGRect imageDrawRect;  
  104.                 imageDrawRect.size = image.size;  
  105.                 /* 
  106.                  * 这才是放置图片的真正坐标 
  107.                  */  
  108.                 // 设置图片的在X坐标的位置  
  109.                 // imageDrawRect.origin.x = runRect.origin.x + lineOrigin.x;  
  110.                 // 将图片放在Label的中间  
  111.                 imageDrawRect.origin.x = (self.bounds.size.width - image.size.width) / 2;  
  112.                 // 设置图片在y坐标的位置  
  113.                 imageDrawRect.origin.y = lineOrigin.y;  
  114.                 // 绘制图片  
  115.                 CGContextDrawImage(context, imageDrawRect, image.CGImage);  
  116.                   
  117.                   
  118.                   
  119.             }  
  120.               
  121.               
  122.               
  123.         }  
  124.           
  125.     }  
  126.       
  127.       
  128. }  


最终效果:


每日更新关注:http://weibo.com/hanjunqiang  新浪微博


原文地址:http://blog.csdn.net/qq_31810357/article/details/50124869