您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

CoreText 實作富文本:圖文混排與文字點擊事件

編輯:iOS 相關資訊

要做一個類似微博的富文本段落——文字中穿插表情圖,某些片段還能點擊——CoreText 是最合適的工具。本文說明兩個核心技巧的實作思路。

一、圖文混排的核心想法

CoreText 本身只負責排字,不認得圖片。所以做法是:把該放圖的位置換成一個空白字元佔位,透過 CTRunDelegate 動態告訴排版引擎「這個空格要預留多少寬與高」,再給這些佔位字元打上一個自訂屬性(例如 imageName),繪製時就能分辨哪些空格代表圖片、哪些只是普通空格。

點擊事件的關鍵則是:把觸碰座標換算成「本文的第幾個字元」,再判斷這個索引是否落在需要回應的區間內。

二、組裝帶屬性的文字

-(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];

    // 段落樣式:逐字元換行
    CTLineBreakMode lineBreak = kCTLineBreakByCharWrapping;
    CTParagraphStyleSetting setting;
    setting.spec = kCTParagraphStyleSpecifierLineBreakMode;
    setting.value = &lineBreak;
    setting.valueSize = sizeof(CTLineBreakMode);

    CTParagraphStyleSetting settings[] = { setting };
    CTParagraphStyleRef style = CTParagraphStyleCreate(settings, 1);
    [content addAttribute:(id)kCTParagraphStyleAttributeName
                    value:(id)style
                    range:NSMakeRange(0, [content length])];

    // 需要高亮(可點擊)的片段,這裡直接指定前 10 個字
    [content addAttribute:(id)kCTForegroundColorAttributeName
                    value:(id)[[UIColor blueColor] CGColor]
                    range:NSMakeRange(0, 10)];
}

三個回調函式中,真正有內容的是 ascent 與 width——它們決定圖片佔位的大小:

CGFloat RunDelegateGetAscentCallback(void *refCon) {
    NSString *imageName = (NSString *)refCon;
    return [UIImage imageNamed:imageName].size.height;
}

CGFloat RunDelegateGetDescentCallback(void *refCon) { return 0; }

CGFloat RunDelegateGetWidthCallback(void *refCon) {
    NSString *imageName = (NSString *)refCon;
    return [UIImage imageNamed:imageName].size.width;
}

void RunDelegateDeallocCallback(void *refCon) { }

三、繪製

drawRect 裡有幾個必要步驟:先建立 framesetter 與路徑,把內容畫上去,然後遍歷每一行、每一個 CTRun,找出帶有 imageName 的那些,在它們的位置貼圖。

- (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);
        CGPoint lineOrigin = lineOrigins[i];
        CFArrayRef runs = CTLineGetGlyphRuns(line);

        for (int j = 0; j < CFArrayGetCount(runs); j++) {
            CTRunRef run = CFArrayGetValueAtIndex(runs, j);
            NSDictionary *attributes = (NSDictionary *)CTRunGetAttributes(run);

            CGFloat runAscent, runDescent;
            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 = CGRectMake(runRect.origin.x + lineOrigin.x,
                                                      lineOrigin.y,
                                                      image.size.width, image.size.height);
                    CGContextDrawImage(context, imageDrawRect, image.CGImage);
                }
            }
        }
    }

    CGContextRestoreGState(context);
}

把 _frame 存成實例變項很重要,因為下一個步驟——手勢處理——還要拿它來做座標反查。

四、把點擊位置換算成字元索引

-(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);

        // 注意這裡的 y 軸換算:CoreText 由下往上,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];
    }
}

成果

實作上的關鍵點

第一,座標系翻轉是頭號陷阱。CoreText 的原點在左下,UIKit 在左上,忘記處理就會得到上下顛倒或完全對不上的結果。

第二,行定位不能只比 y,還要比 x。上面範例用簡化條件判斷,正式專案裡更穩妥的做法是先找出 y 落在該行範圍(considering ascent 與 descent)的那些行,再用 CTLineGetStringIndexForPosition 求 x 方向的索引。

第三,範例中的可點擊範圍是寫死的 1~10。實務上你應該在組裝 attributed string 時,就把「可點擊區間」與其對應的動作(打開連結、跳轉話題)存成一份範圍清單,點擊時反查這份清單,才能支援多段、多種行為。

最後,若你的需求只是「一段文字裡有可點連結」,iOS 7 之後的 UITextView 已原生支援 data detector 與 link 屬性,能省下大量功夫。CoreText 的價值在於更細緻的控制——自訂行距、精準的圖文對齊、或完全自繪的排版邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved