coreText自定義富文本Label

UILabel是經常使用的一種控件,iOS上的UILabel已經能很好滿足一些需求。比如設置對齊方式,換行模式等等。

但如果需求是需要一串字符中不同的字符顏色,字體都單獨設置,UILabel就無法滿足了。那就自己來做個富文本Label好了。

先創建繼承UILabel的AttributedLabel.h,AttributedLabel.m文件,重載UILabeld -(void)drawTextInRect:(CGRect)rect方法,我們的文本繪製就放在這個函數中。

使用coreText進行文本繪製,需要在工程中添加CoreText.framework,然後在AttributedLabel.m裏import<CoreText/CoreText.h>就可以使用了。coreText負責繪製,那繪製的內容和屬性則要靠NSAttributedString來存儲,如果屬性具有不確定性,可以使用NSMutableAttributedString,方便後面添加屬性。

先來看下如何創建一個具有兩個顏色,兩種字體的“hello world”的NSMutableAttributedString實例。

  1. NSString *text = @“hello word”;
  2.  
  3. NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text];
  4.  
  5. [attributedText addAttribute:(NSString*)(kCTForegroundColorAttributeName) value:(id)[[UIColor blueColor]CGColor] range:NSMakeRange(0,5)];
  6.  
  7. [attributedText addAttribute:(NSString*)(kCTForegroundColorAttributeName) value:(id)[[UIColor redColor]CGColor] range:NSMakeRange(6,5)];
  8.  
  9. CTFontRef  font_hello = CTFontCreateWithName((CFStringRef)@“Helvetica”,16,NULL);
  10.  
  11. CTFontRef  font_world = CTFontCreateWithName((CFStringRef)@“GillSans”,20,NULL);
  12.  
  13. [attributedText addAttribute: (NSString*)(kCTFontAttributeName) value:(id)font_hello range:NSMakeRange(0,5)];
  14.  
  15. [attributedText addAttribute: (NSString*)(kCTFontAttributeName) value:(id)font_world range:NSMakeRange(6,5)];

這樣,一個包含簡單繪製屬性的NSMutableAttributedString實例就創建出來了。

接下來就要在drawTextInRect函數中開始繪製了。

普通視圖座標系原點在左上方,而QuartZ繪圖的座標系原點在左下方,所以我們先要調整座標系。

  1. CGContextRef context = UIGraphicsGetCurrentContext();
  2.  
  3. CGContextSetTextMatrix(context,CGAffineTransformIdentity);//重置
  4.  
  5. CGContextTranslateCTM(context,0,self.bounds.size.height); //y軸高度
  6.  
  7. CGContextScaleCTM(context,1.0,-1.0);//y軸翻轉

好了,可以開始繪製,因爲”hello world”較短,一行就可以放下,那麼可以這麼繪製

  1. CTLineRef line = CTLineCreateWithAttributedString(attributedText);
  2.  
  3. CGContextSetTextPosition(context,0,0);
  4.  
  5. CTLineDraw(line,context);
  6.  
  7. CFRelease(line);

OK,就這麼多搞定。

那如果文本很長,希望換行來顯示怎麼辦?

那我們先要給attributedText添加些關於行相關屬性。

下面都是基本的,可以根據自己繪製情況調整,擴充相應的變量。

  1. CTLineBreakMode lineBreakMode = kCTLineBreakByWordWrapping;//換行模式
  2.  
  3. CTTextAlignment alignment = kCTLeftTextAlignment;//對齊方式
  4.  
  5. float lineSpacing =2.0;//行間距
  6.  
  7. CTParagraphStyleSetting paraStyles[3] = {
  8.  
  9. {.spec = kCTParagraphStyleSpecifierLineBreakMode,.valueSize = sizeof(CTLineBreakMode), .value = (const void*)&lineBreakMode},
  10.  
  11. {.spec = kCTParagraphStyleSpecifierAlignment,.valueSize = sizeof(CTTextAlignment), .value = (const void*)&alignment},
  12.  
  13. {.spec = kCTParagraphStyleSpecifierLineSpacing,.valueSize = sizeof(CGFloat), .value = (const void*)&lineSpacing},
  14.  
  15. };
  16.  
  17. CTParagraphStyleRef style = CTParagraphStyleCreate(paraStyles,3);
  18.  
  19. [attributedText addAttribute:(NSString*)(kCTParagraphStyleAttributeName) value:(id)style range:NSMakeRange(0,[text length])];
  20.  
  21. CFRelease(style);

下面就可以繪製了

  1. CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributedText);
  2.  
  3. CGMutablePathRef path = CGPathCreateMutable();
  4.  
  5. CGPathAddRect(path,NULL,self.bounds);
  6.  
  7. CTFrameRef frame = CTFramesetterCreateFrame(framesetter,CFRangeMake(0,0),path,NULL);
  8.  
  9. CGContextSetTextPosition(context,0,0);
  10.  
  11. CTFrameDraw(frame,context);
  12.  
  13. CFRelease(framesetter);
  14.  
  15. CFRelease(frame);

這樣繪製出來的可以自適應換行了,或者可以做的複雜點,通過上面獲取的CTFrameRef frame來得到CTLineRef繪製

  1. CFArrayRef lines = CTFrameGetLines(frame);
  2.  
  3. int lineNumber = CFArrayGetCount(lines);
  4.  
  5. CGPoint lineOrigins[lineNumber];
  6.  
  7. CTFrameGetLineOrigins(frame,CFRangeMake(0,lineNumber), lineOrigins);
  8.  
  9. for(int lineIndex = 0;lineIndex < lineNumber;lineIndex++){
  10.  
  11. CGPoint lineOrigin = lineOrigins[lineIndex];
  12.  
  13. CTLineRef line = CFArrayGetValueAtIndex(lines,lineIndex);
  14.  
  15. CGContextSetTextPosition(context,lineOrigin.x,lineOrigin.y);
  16.  
  17. CTLineDraw(line,context);
  18.  
  19. }

但這樣繪製方法有個問題,就是即使行間距設爲0.0(不能爲負值)仍是比較分散的。如果希望更進一步控制好行間距,那自己就一行一行計算位置畫

  1. float lineHeight = 20; //行高
  2.  
  3. BOOL drawFlag = YES;//是否繪製
  4.  
  5. int lineCount = 0//行數
  6.  
  7. CFIndex currentIndex = 0;//繪製計數
  8.  
  9. CTTypesetterRef typeSetter = CTTypesetterCreateWithAttributedString((CFAttributedStringRef)attributedText);
  10.  
  11. float fontAscender = MAX(font_hello.ascender,font_world.ascender);
  12.  
  13. float y = self.bounds.origin.y+self.bounds.size.height-fontAscender;
  14.  
  15. while(drawFlag)
  16.  
  17. {
  18.  
  19. CFIndex lineLength = CTTypesetterSuggestLineBreak(typeSetter,currentIndex,self.bounds.size.width);
  20.  
  21. CFRange lineRange = CFRangeMake(currentIndex,lineLength);
  22.  
  23. CTLineRef line = CTTypesetterCreateLine(typeSetter,lineRange);
  24.  
  25. float x = CTLineGetPenOffsetForFlush(line,0,self.bounds.size.width);
  26.  
  27. CGContextSetTextPosition(context,x,y);
  28.  
  29. CTLineDraw(line,context);
  30.  
  31. if(currentIndex + lineLength >= [text length]){
  32.  
  33. drawFlag = NO;
  34.  
  35. }
  36.  
  37. CFRelease(line);
  38.  
  39. count++;
  40.  
  41. -=lineHeight;
  42.  
  43. currentIndex += lineLength;
  44.  
  45. }
  46.  
  47. CFRelease(typeSetter);

到這裏的時候,又有個問題,就是用同樣的字體和字號,繪製的字總是會比UILabel顯示的粗些。

查看kCTStrokeWidthAttributeName屬性發現默認已經爲0.0,但這個值是可以爲負值,那就變通的解決這個問題。

在attributedText裏添加兩個屬性值

  1. CGFloat widthValue = -1.0;
  2.  
  3. CFNumberRef strokeWidth = CFNumberCreate(NULL,kCFNumberFloatType,&widthValue);
  4.  
  5. [attributedText addAttribute:(NSString*)(kCTStrokeWidthAttributeName) value:(id)strokeWidth range:NSMakeRange(0,[text length])];
  6.  
  7. [attributedText addAttribute:(NSString*)(kCTStrokeColorAttributeName) value:(id)[[UIColor whiteColor]CGColor] range:NSMakeRange(0,[text length])];

這樣繪製出來的字就細緻些。

好了,沿着這條線的內容大致說完,有興趣的自己敲一敲吧

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章