coretext 使用

  -(void)drawRect:(CGRect)rect
{
  [super drawRect:rect];
  //  开启上下文
  CGContextRef context = UIGraphicsGetCurrentContext();
  // 翻转坐标轴
  CGContextSetTextMatrix(context, CGAffineTransformIdentity);
  CGContextTranslateCTM(context, 0, self.bounds.size.height);
  CGContextScaleCTM(context, 1.0, -1.0);
  // 创建 富文本字符串
  NSMutableAttributedString * attributeStr = [[NSMutableAttributedString alloc] initWithString:@"\n这里在测试图文混排,\n我是一个富文本"];
  
  // CTRun 的回调//创建一个回调结构体,设置相关参数
  CTRunDelegateCallbacks callBacks;
  //memset将已开辟内存空间 callbacks 的首 n 个字节的值设为值 0, 相当于对CTRunDelegateCallbacks内存空间初始化
  memset(&callBacks,0,sizeof(CTRunDelegateCallbacks));
  
  callBacks.version = kCTRunDelegateVersion1;//设置回调版本,默认这个
  /**
   *创建三个代理方法  拿到图片的 长和 宽
   */
  callBacks.getAscent = ascentCallBacks;//设置图片顶部距离基线的距离
  callBacks.getDescent = descentCallBacks;//设置图片底部距离基线的距离
  callBacks.getWidth = widthCallBacks;//设置图片宽度
  
  /*
   创建一个代理
  */
  
  NSDictionary * dicPic = @{@"height":@129,@"width":@400};//创建一个图片尺寸的字典,初始化代理对象需要
  CTRunDelegateRef delegate = CTRunDelegateCreate(& callBacks, (__bridge void *)dicPic);//创建代理
  /**
   *图片的插入
   */
  unichar placeHolder = 0xFFFC; //创建空白字符
  NSString * placeHolderStr = [NSString stringWithCharacters:&placeHolder length:1];//已空白字符生成字符串
  NSMutableAttributedString * placeHolderAttrStr = [[NSMutableAttributedString alloc] initWithString:placeHolderStr]; //用字符串初始化占位符的富文本
  ///设置代理
  CFAttributedStringSetAttribute((CFMutableAttributedStringRef)placeHolderAttrStr, CFRangeMake(0, 1), kCTRunDelegateAttributeName, delegate);//给字符串中的范围中字符串 设置代理
  
  CFRelease(delegate);//释放(__bridge进行C与OC数据类型的转换,C为非ARC,需要手动管理)
  
  [attributeStr insertAttributedString:placeHolderAttrStr atIndex:12];//将占位符插入原富文本
  /**
   *绘制文本
   */
  CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributeStr);//一个frame的工厂,负责生成frame
  
  CGMutablePathRef path = CGPathCreateMutable();//创建绘制区域
  CGPathAddRect(path, NULL, self.bounds);//添加绘制尺寸
  
  NSInteger length = attributeStr.length;
  CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, length), path, NULL);
  CTFrameDraw(frame, context);
  
  
  UIImage * image = [UIImage imageNamed:@"bd_logo1"];
  CGRect imgFrm = [self calculateImageRectWithFrame:frame];
  CGContextDrawImage(context,imgFrm, image.CGImage);//绘制图片
  CFRelease(frame);
  CFRelease(path);
  CFRelease(frameSetter);
}
#pragma mark  ---- 代理方法

static CGFloat ascentCallBacks(void * ref)
{
  return [(NSNumber *)[(__bridge NSDictionary *)ref valueForKey:@"height"] floatValue];
}
static CGFloat descentCallBacks(void * ref)
{
  return 0;
}
static CGFloat widthCallBacks(void * ref)
{
  return [(NSNumber *)[(__bridge NSDictionary *)ref valueForKey:@"width"] floatValue];
}


-(CGRect)calculateImageRectWithFrame:(CTFrameRef)frame
{
  NSArray * arrLines = (NSArray *)CTFrameGetLines(frame);
  NSInteger count = [arrLines count];
  CGPoint points[count];
  CTFrameGetLineOrigins(frame, CFRangeMake(0, 0), points);
  for (int i = 0; i < count; i ++) {
      CTLineRef line = (__bridge CTLineRef)arrLines[i];
      NSArray * arrGlyphRun = (NSArray *)CTLineGetGlyphRuns(line);
      for (int j = 0; j < arrGlyphRun.count; j ++) {
          CTRunRef run = (__bridge CTRunRef)arrGlyphRun[j];
          NSDictionary * attributes = (NSDictionary *)CTRunGetAttributes(run);            CTRunDelegateRef delegate = (__bridge CTRunDelegateRef)[attributes valueForKey:(id)kCTRunDelegateAttributeName];
          if (delegate == nil) {
              continue;
          }
          NSDictionary * dic = CTRunDelegateGetRefCon(delegate);
          if (![dic isKindOfClass:[NSDictionary class]]) {
              continue;
          }
          CGPoint point = points[i];
          CGFloat ascent;
          CGFloat descent;
          CGRect boundsRun;
          boundsRun.size.width = CTRunGetTypographicBounds(run, CFRangeMake(0, 0), &ascent, &descent, NULL);
          boundsRun.size.height = ascent + descent;
          CGFloat xOffset = CTLineGetOffsetForStringIndex(line, CTRunGetStringRange(run).location, NULL);
          boundsRun.origin.x = point.x + xOffset;
          boundsRun.origin.y = point.y - descent;
          CGPathRef path = CTFrameGetPath(frame);
          CGRect colRect = CGPathGetBoundingBox(path);
          CGRect imageBounds = CGRectOffset(boundsRun, colRect.origin.x, colRect.origin.y);
          return imageBounds;
      }
  }
  return CGRectZero;
}





  ```
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • CoreText 框架中最常用的几个类 CTFont CTFontCollection CTFontDescrip...
    神采飞扬_2015阅读 4,813评论 1 11
  • CoreText是iOS/OSX中文本显示的一个底层框架,它是用C语言写成的,有快速简单的优势。iOS中的Text...
    小猫仔阅读 10,450评论 2 9
  • https://developer.apple.com/documentation/coretext // 官方文...
    Avery_AN阅读 5,300评论 0 0
  • iOS中的文字渲染 在iOS出现早期,显示特性文本唯一可行的办法就是使用UIWebView和利用HTML来处理定制...
    正谦阅读 4,143评论 0 1
  • 什么是异步绘制?在子线程中绘制需要显示的内容、不占用主线程资源以防绘制的过程中阻塞主线程。对UIView来说即绘制...
    Avery_AN阅读 5,247评论 0 2

友情链接更多精彩内容