本例模擬類似微博的富文本效果,既要在文字流中嵌入圖片,又要能響應對特定文字段的點擊。核心思路有兩條:用占位字符加 CTRunDelegate 撐開圖片的位置,用字符下標反查點擊命中的範圍。
先把需要放圖片的位置用一個空格之類的占位字符替換,然後為這個字符綁定 CTRunDelegate,通過回調動態告訴 CoreText「這個字符要佔多寬、多高」,數值即圖片尺寸。接著給它掛一個自定義屬性名(示例中用 imageName),渲染時就能把「代表圖片的占位符」和「普通空格」區分開,前者畫圖,後者留白。
CoreText 並沒有自帶點擊 API,需要自己判斷:觸摸點落在第幾行,該行內對應第幾個字符,這個字符下標是否落在需要響應的字符串區間內。命中則觸發相應行為。
// 創建 NSMutableAttributedString,標記所有可點擊文字與需要替換為圖片的位置
- (void)buildAttribute
{
content = [[NSMutableAttributedString alloc] initWithString:originalStr];
NSString *imgName = @"smile.png";
// 準備 CTRun 回調,用於動態設置圖片占位區域的寬高
CTRunDelegateCallbacks imageCallbacks;
imageCallbacks.version = kCTRunDelegateVersion1;
imageCallbacks.dealloc = RunDelegateDeallocCallback;
imageCallbacks.getAscent = RunDelegateGetAscentCallback;
imageCallbacks.getDescent = RunDelegateGetDescentCallback;
imageCallbacks.getWidth = RunDelegateGetWidthCallback;
CTRunDelegateRef runDelegate = CTRunDelegateCreate(&imageCallbacks, imgName);
// 簡化處理:直接用一個空格作為圖片占位符
NSMutableAttributedString *imageAttributedString = [[NSMutableAttributedString alloc] initWithString:@" "];
[imageAttributedString addAttribute:(NSString *)kCTRunDelegateAttributeName
value:(id)runDelegate
range:NSMakeRange(0, 1)];
CFRelease(runDelegate);
// 掛上自定義屬性,渲染時用來辨識這是圖片占位符
[imageAttributedString addAttribute:@"imageName" value:imgName range:NSMakeRange(0, 1)];
[content appendAttributedString:imageAttributedString];
// 段落樣式:按字符換行
CTParagraphStyleSetting lineBreakMode;
CTLineBreakMode lineBreak = kCTLineBreakByCharWrapping;
lineBreakMode.spec = kCTParagraphStyleSpecifierLineBreakMode;
lineBreakMode.value = &lineBreak;
lineBreakMode.valueSize = sizeof(CTLineBreakMode);
CTParagraphStyleSetting settings[] = { lineBreakMode };
CTParagraphStyleRef style = CTParagraphStyleCreate(settings, 1);
NSMutableDictionary *attributes =
[NSMutableDictionary dictionaryWithObject:(id)style forKey:(id)kCTParagraphStyleAttributeName];
[content addAttributes:attributes range:NSMakeRange(0, [content length])];
// 為可點擊文字設置高亮顏色,此處簡化為硬編碼前 10 個字符
[content addAttribute:(id)kCTForegroundColorAttributeName
value:(id)[[UIColor blueColor] CGColor]
range:NSMakeRange(0, 10)];
}
void RunDelegateDeallocCallback(void *refCon)
{
}
CGFloat RunDelegateGetAscentCallback(void *refCon)
{
NSString *imageName = (NSString *)refCon;
return 30; // return [UIImage imageNamed:imageName].size.height;
}
CGFloat RunDelegateGetDescentCallback(void *refCon)
{
return 0;
}
CGFloat RunDelegateGetWidthCallback(void *refCon)
{
NSString *imageName = (NSString *)refCon;
return 30; // return [UIImage imageNamed:imageName].size.width;
}
- (void)drawRect:(CGRect)rect
{
[self buildAttribute];
CGContextRef context = UIGraphicsGetCurrentContext();
// CoreText 的坐標系原點在左下,需要做一次翻轉以適配 UIKit
CGContextSaveGState(context);
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, rect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)content);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(0, 0, rect.size.width, rect.size.height));
_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);
for (int i = 0; i < CFArrayGetCount(lines); i++) {
CTLineRef line = CFArrayGetValueAtIndex(lines, i);
CGFloat lineAscent, lineDescent, lineLeading;
CTLineGetTypographicBounds(line, &lineAscent, &lineDescent, &lineLeading);
CFArrayRef runs = CTLineGetGlyphRuns(line);
for (int j = 0; j < CFArrayGetCount(runs); j++) {
CGFloat runAscent, runDescent;
CGPoint lineOrigin = lineOrigins[i];
CTRunRef run = CFArrayGetValueAtIndex(runs, j);
NSDictionary *attributes = (NSDictionary *)CTRunGetAttributes(run);
CGRect runRect;
runRect.size.width = CTRunGetTypographicBounds(run, CFRangeMake(0, 0),
&runAscent, &runDescent, NULL);
runRect = CGRectMake(lineOrigin.x + CTLineGetOffsetForStringIndex(line,
CTRunGetStringRange(run).location, NULL),
lineOrigin.y - runDescent,
runRect.size.width,
runAscent + runDescent);
NSString *imageName = [attributes objectForKey:@"imageName"];
if (imageName) {
UIImage *image = [UIImage imageNamed:imageName];
if (image) {
CGRect imageDrawRect;
imageDrawRect.size = CGSizeMake(30, 30);
imageDrawRect.origin.x = runRect.origin.x + lineOrigin.x;
imageDrawRect.origin.y = lineOrigin.y;
CGContextDrawImage(context, imageDrawRect, image.CGImage);
}
}
}
}
CGContextRestoreGState(context);
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:self];
CFArrayRef lines = CTFrameGetLines(_frame);
CGPoint origins[CFArrayGetCount(lines)];
CTFrameGetLineOrigins(_frame, CFRangeMake(0, 0), origins);
CTLineRef line = NULL;
CGPoint lineOrigin = CGPointZero;
for (int i = 0; i < CFArrayGetCount(lines); i++) {
CGPoint origin = origins[i];
CGPathRef path = CTFrameGetPath(_frame);
CGRect rect = CGPathGetBoundingBox(path);
// 坐標換算,把行原點轉到 UIKit 體系
CGFloat y = rect.origin.y + rect.size.height - origin.y;
if ((location.y <= y) && (location.x >= origin.x)) {
line = CFArrayGetValueAtIndex(lines, i);
lineOrigin = origin;
break;
}
}
location.x -= lineOrigin.x;
// 反查點擊位置對應的字符下標
CFIndex index = CTLineGetStringIndexForPosition(line, location);
// 判斷是否落在需要響應的區間內
if (index >= 1 && index <= 10) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"click event"
message:[originalStr substringWithRange:NSMakeRange(0, 10)]
delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
[alert show];
}
}
示例中圖片尺寸與可點擊範圍均為硬編碼,實戰中應改為解析文本標記(如 [表情名])動態生成,並緩存 CTRun 位置信息以提升點擊響應速度。另外 UIAlertView 在 iOS 9 之後已被廢棄,新項目請改用 UIAlertController;CTParagraphStyleRef 與 framesetter 用完也記得 CFRelease,否則在長列表反覆重繪時會造成內存持續增長。