iOS 圖文混排(富文本)

富文本繪制步驟

  1. 首先需要一個(gè) StringA匕垫;
  2. 把 StringA 轉(zhuǎn)成 attributeString雏门,并添加相關(guān)樣式泞莉;
  3. 生成 CTFramessetter,得到 CTFrame钾麸;
  4. 繪制 CTFrameDraw更振。

繪制完成后,因?yàn)槔L制只是顯示饭尝,其他的需要額外操作肯腕。
響應(yīng)相關(guān)點(diǎn)擊事件原理:
CTFrame 包含了多個(gè) CTLine,并且可以得到每個(gè) line 的起始位置和大小钥平,計(jì)算出響應(yīng)的區(qū)域范圍乎芳,然后根據(jù)點(diǎn)擊坐標(biāo)來(lái)判斷是否在響應(yīng)區(qū)。
又如圖片顯示原理:
先用空白占位符將位置保留出來(lái)帖池,然后再添加圖片和其他奈惑。

富文本繪制需要引入框架 #import <CoreText/CoreText.h>

自定義 label,在自定義 label 中按照繪制出來(lái)的文字獲取信息(位置)睡汹。

- (void)drawRect:(CGRect)rect {
    
    // 富文本字符串
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:self.text attributes:nil];
    // 添加屬性
    [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, self.text.length)];
    NSRange sepRange = NSMakeRange(40, 5);
    [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:sepRange];
    
    // 生成 CTFrame
    CTFramesetterRef framesetterRef = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attrStr);
    CGPathRef pathRef = CGPathCreateWithRect(CGRectMake(0, 0, self.frame.size.width, self.frame.size.height), &CGAffineTransformIdentity);
    
    CTFrameRef frameRef = CTFramesetterCreateFrame(framesetterRef, CFRangeMake(0, 0), pathRef, nil);
    
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    
    // 調(diào)整坐標(biāo)
    CGContextSetTextMatrix(contextRef, CGAffineTransformIdentity);
    CGContextTranslateCTM(contextRef, 0, self.frame.size.height);
    CGContextScaleCTM(contextRef, 1, -1);

    // 繪制
    CTFrameDraw(frameRef, contextRef);
    
    
    // 獲取信息
    NSArray *lineArr = (__bridge NSArray *)CTFrameGetLines(frameRef);
    
    CGPoint pointArr[lineArr.count];
    memset(pointArr, 0, sizeof(pointArr));
    CTFrameGetLineOrigins(frameRef, CFRangeMake(0, 0), pointArr); // 由于坐標(biāo)系關(guān)系肴甸, 不直接通過(guò)這種方式拿行(CTLine)的起始位置
    
    double heightAddup = 0; // Y
    // CTLine 信息
    for (int i = 0 ; i < lineArr.count; i++) {
        
        CTLineRef lineRef = (__bridge CTLineRef)lineArr[i];
        NSArray *runArr = (__bridge NSArray *)CTLineGetGlyphRuns(lineRef);
        
        CGFloat ascent = 0;     // 上行高度
        CGFloat descent = 0;    // 下行高度
        CGFloat lineGap = 0;    // 行間距
        CTLineGetTypographicBounds(lineRef, &ascent, &descent, &lineGap);
        
        double startX = 0;
        // CTRun 信息
        // 字的高度
        double runHeight = ascent + descent + lineGap;
        for (int j = 0; j < runArr.count; j++) {
            
            CTRunRef runRef = (__bridge CTRunRef)runArr[j];
            CFRange runRange = CTRunGetStringRange(runRef);
            double runWidth = CTRunGetTypographicBounds(runRef, CFRangeMake(0, 0), 0, 0, 0);
            if (runRange.location == sepRange.location && runRange.length == sepRange.length) {
                NSLog(@"找到位置"); // 計(jì)算需要的位置和 rect
                NSLog(@"x:%f...y:%f...w:%f...h:%f", startX, heightAddup, runWidth, runHeight);
                sepRect = CGRectMake(startX, heightAddup, runWidth, runHeight);
            }
            startX += runWidth;
        }
        
        // 字的高度疊加
        heightAddup += runHeight;
    }
    
}

找到位置之后就可以添加點(diǎn)擊事件了。

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    if (CGRectContainsPoint(sepRect, point)) {
        NSLog(@"點(diǎn)擊了紅色的文字");
    }
    
}

不要忘了將 label 的userInteractionEnabled屬性設(shè)置為 YES囚巴。

或者在找到的位置上添加 button原在,然后給 button 設(shè)置事件。

含圖片的富文本

#define YYCoreTextImageWidthPro @"YYCoreTextImageWidthPro"
#define YYCoreTextImageHeightPro @"YYCoreTextImageHeightPro"

static CGFloat ctRunDelegateGetWidthCallback(void *refCon) {
    NSDictionary *infoDict = (__bridge NSDictionary *)(refCon);
    if ([infoDict isKindOfClass:[NSDictionary class]]) {
        return [infoDict[YYCoreTextImageWidthPro] floatValue];
    }
    return 0;
}
static CGFloat ctRunDelegateGetAscentCallback(void *refCon) {
    NSDictionary *infoDict = (__bridge NSDictionary *)(refCon);
    if ([infoDict isKindOfClass:[NSDictionary class]]) {
        return [infoDict[YYCoreTextImageHeightPro] floatValue];
    }
    return 0;
}
static CGFloat ctRunDelegateGetDescentCallback(void *refCon) {
    return 0;
}

static NSMutableDictionary *argDic = nil;

@implementation YYImageLabel
{
    NSInteger imageSpaceIndex;
    CGRect sepRect;
    UIImageView *_imageView;
}

- (void)drawRect:(CGRect)rect {
    
    // 富文本字符串
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:self.text attributes:nil];
    // 添加屬性
    [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, self.text.length)];
    
    // 圖片占位符
    imageSpaceIndex = self.text.length;
    [attrStr appendAttributedString:[self sepImageSpaceWidth:50 height:30]];
    
    NSMutableAttributedString *textAttrStr = [[NSMutableAttributedString alloc] initWithString:@"bhiuhsdfiohsifwfd" attributes:nil];
    [attrStr appendAttributedString:textAttrStr];
    
    // 生成 CTFrame
    CTFramesetterRef framesetterRef = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attrStr);
    CGPathRef pathRef = CGPathCreateWithRect(CGRectMake(0, 0, self.frame.size.width, self.frame.size.height), &CGAffineTransformIdentity);
    
    CTFrameRef frameRef = CTFramesetterCreateFrame(framesetterRef, CFRangeMake(0, 0), pathRef, nil);
    
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    
    // 調(diào)整坐標(biāo)
    CGContextSetTextMatrix(contextRef, CGAffineTransformIdentity);
    CGContextTranslateCTM(contextRef, 0, self.frame.size.height);
    CGContextScaleCTM(contextRef, 1, -1);
    
    // 繪制
    CTFrameDraw(frameRef, contextRef);
    
    
    // 獲取信息
    NSArray *lineArr = (__bridge NSArray *)CTFrameGetLines(frameRef);
    
    CGPoint pointArr[lineArr.count];
    memset(pointArr, 0, sizeof(pointArr));
    CTFrameGetLineOrigins(frameRef, CFRangeMake(0, 0), pointArr); // 由于坐標(biāo)系關(guān)系彤叉, 不直接通過(guò)這種方式拿行(CTLine)的起始位置
    
    double heightAddup = 0; // Y
    // CTLine 信息
    for (int i = 0 ; i < lineArr.count; i++) {
        
        CTLineRef lineRef = (__bridge CTLineRef)lineArr[i];
        NSArray *runArr = (__bridge NSArray *)CTLineGetGlyphRuns(lineRef);
        
        CGFloat ascent = 0;     // 上行高度
        CGFloat descent = 0;    // 下行高度
        CGFloat lineGap = 0;    // 行間距
        CTLineGetTypographicBounds(lineRef, &ascent, &descent, &lineGap);
        
        double startX = 0;
        // CTRun 信息
        // 字的高度
        double runHeight = ascent + descent + lineGap;
        for (int j = 0; j < runArr.count; j++) {
            
            CTRunRef runRef = (__bridge CTRunRef)runArr[j];
            CFRange runRange = CTRunGetStringRange(runRef);
            double runWidth = CTRunGetTypographicBounds(runRef, CFRangeMake(0, 0), 0, 0, 0);
            if (imageSpaceIndex == runRange.location && imageSpaceIndex < runRange.location + runRange.length) {
                NSLog(@"找到位置"); // 計(jì)算需要的位置和 rect
                NSLog(@"x:%f...y:%f...w:%f...h:%f", startX, heightAddup, runWidth, runHeight);
                sepRect = CGRectMake(startX, heightAddup, runWidth, runHeight);
            }
            startX += runWidth;
        }
        
        // 字的高度疊加
        heightAddup += runHeight;
    }
    [self setNeedsLayout];
}

- (void)layoutSubviews {
    if (sepRect.size.width > 0) {
        if (!_imageView) {
            _imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1.png"]];
            [self addSubview:_imageView];
        }
        [_imageView setFrame:sepRect];
    }
}

- (NSMutableAttributedString *)sepImageSpaceWidth:(float)width height:(float)height {
    
    CTRunDelegateCallbacks callbacks;
    memset(&callbacks, 0, sizeof(CTRunDelegateCallbacks));
    
    callbacks.getWidth = ctRunDelegateGetWidthCallback;
    callbacks.getAscent = ctRunDelegateGetAscentCallback;
    callbacks.getDescent = ctRunDelegateGetDescentCallback; // 0
    callbacks.version = kCTRunDelegateVersion1;
    
    // 創(chuàng)建占位符
    NSMutableAttributedString *spaceAttrStr = [[NSMutableAttributedString alloc] initWithString:@" "];
    // 參數(shù)動(dòng)態(tài)化
    argDic = [NSMutableDictionary dictionary];
    [argDic setValue:@(width) forKey:YYCoreTextImageWidthPro];
    [argDic setValue:@(height) forKey:YYCoreTextImageHeightPro];
    CTRunDelegateRef runDelegateRef = CTRunDelegateCreate(&callbacks, (__bridge void *)argDic);
    
    // 配置占位的屬性
    CFAttributedStringSetAttribute((CFMutableAttributedStringRef)spaceAttrStr, CFRangeMake(0, 1), kCTRunDelegateAttributeName, runDelegateRef);
    
    return spaceAttrStr;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末庶柿,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子秽浇,更是在濱河造成了極大的恐慌浮庐,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,451評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件柬焕,死亡現(xiàn)場(chǎng)離奇詭異审残,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)斑举,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,172評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門(mén)搅轿,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人富玷,你說(shuō)我怎么就攤上這事璧坟。” “怎么了赎懦?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,782評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵雀鹃,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我铲敛,道長(zhǎng)褐澎,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,709評(píng)論 1 294
  • 正文 為了忘掉前任伐蒋,我火速辦了婚禮工三,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘先鱼。我一直安慰自己俭正,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,733評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布焙畔。 她就那樣靜靜地躺著掸读,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上儿惫,一...
    開(kāi)封第一講書(shū)人閱讀 51,578評(píng)論 1 305
  • 那天澡罚,我揣著相機(jī)與錄音,去河邊找鬼肾请。 笑死留搔,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的铛铁。 我是一名探鬼主播隔显,決...
    沈念sama閱讀 40,320評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼饵逐!你這毒婦竟也來(lái)了括眠?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,241評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤倍权,失蹤者是張志新(化名)和其女友劉穎掷豺,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體账锹,經(jīng)...
    沈念sama閱讀 45,686評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡萌业,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,878評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了奸柬。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片生年。...
    茶點(diǎn)故事閱讀 39,992評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖廓奕,靈堂內(nèi)的尸體忽然破棺而出抱婉,到底是詐尸還是另有隱情,我是刑警寧澤桌粉,帶...
    沈念sama閱讀 35,715評(píng)論 5 346
  • 正文 年R本政府宣布蒸绩,位于F島的核電站,受9級(jí)特大地震影響铃肯,放射性物質(zhì)發(fā)生泄漏患亿。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,336評(píng)論 3 330
  • 文/蒙蒙 一押逼、第九天 我趴在偏房一處隱蔽的房頂上張望步藕。 院中可真熱鬧,春花似錦挑格、人聲如沸咙冗。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,912評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)雾消。三九已至灾搏,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間立润,已是汗流浹背狂窑。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,040評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留范删,地道東北人蕾域。 一個(gè)月前我還...
    沈念sama閱讀 48,173評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像到旦,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子巨缘,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,947評(píng)論 2 355