coretext 使用

作者: 京北磊哥 | 来源:发表于2020-12-23 17:44 被阅读0次
  -(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;
}





  ```

相关文章

网友评论

    本文标题:coretext 使用

    本文链接:https://www.haomeiwen.com/subject/zddunktx.html