ios NSAttributedString 詳解

來源:互聯網
上載者:User

標籤:iphone開發   nsattributedstring   


ios NSAttributedString 詳解


NSAttributedString可以讓我們使一個字串顯示的多樣化,但是目前到iOS 5為止,好像對它支援的不是很好,因為顯示起來不太方便(至少沒有在OS X上方便)。

首先匯入CoreText.framework,並在需要使用的檔案中匯入:

#import<CoreText/CoreText.h>

建立一個NSMutableAttributedString:

  1. NSMutableAttributedString *attriString = [[[NSMutableAttributedString alloc] initWithString:@"this is test!"]   
  2.                                               autorelease];  
非常常規的建立方式,接下來我們給它配置屬性:
  1. //把this的字型顏色變為紅色  
  2. [attriString addAttribute:(NSString *)kCTForegroundColorAttributeName  
  3.                     value:(id)[UIColor redColor].CGColor   
  4.                     range:NSMakeRange(0, 4)];  
  5. //把is變為黃色  
  6. [attriString addAttribute:(NSString *)kCTForegroundColorAttributeName  
  7.                     value:(id)[UIColor yellowColor].CGColor   
  8.                     range:NSMakeRange(5, 2)];  
  9. //改變this的字型,value必須是一個CTFontRef  
  10. [attriString addAttribute:(NSString *)kCTFontAttributeName  
  11.                     value:(id)CTFontCreateWithName((CFStringRef)[UIFont boldSystemFontOfSize:14].fontName,  
  12.                                                    14,   
  13.                                                    NULL)  
  14.                     range:NSMakeRange(0, 4)];  
  15. //給this加上底線,value可以在指定的枚舉中選擇  
  16. [attriString addAttribute:(NSString *)kCTUnderlineStyleAttributeName 





  1.                     value:(id)[NSNumber numberWithInt:kCTUnderlineStyleDouble]  
  2.                     range:NSMakeRange(0, 4)];  
  3. return attriString;  

這樣就算是配置好了,但是我們可以發現NSAttributedString繼承於NSObject,並且不支援任何draw的方法,那我們就只能自己draw了。寫一個UIView的子類(假設命名為TView),在initWithFrame中把背景色設為透明(self.backgroundColor = [UIColor clearColor]),然後在重寫drawRect方法:

  1. -(void)drawRect:(CGRect)rect{  
  2.     [super drawRect:rect];  
  3.       
  4.     NSAttributedString *attriString = getAttributedString();  
  5.       
  6.     CGContextRef ctx = UIGraphicsGetCurrentContext();  
  7.     CGContextConcatCTM(ctx, CGAffineTransformScale(CGAffineTransformMakeTranslation(0, rect.size.height), 1.f, -1.f));  
  8.       
  9.     CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attriString);  
  10.     CGMutablePathRef path = CGPathCreateMutable();  
  11.     CGPathAddRect(path, NULL, rect);  
  12.       
  13.     CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);  
  14.     CFRelease(path);  
  15.     CFRelease(framesetter);  
  16.       
  17.     CTFrameDraw(frame, ctx);  
  18.     CFRelease(frame);  
  19. }  

在代碼中我們調整了CTM(current transformation matrix),這是因為Quartz 2D的座標系統不同,比如(10, 10)到(20, 20)的直線座標:

 

座標類似於數學中的座標,可以先不調整CTM,看它是什麼樣子的,下面兩種調整方法是完全一樣的:

  1. CGContextConcatCTM(ctx, CGAffineTransformScale(CGAffineTransformMakeTranslation(0, rect.size.height), 1.f, -1.f));  
==
  1. CGContextTranslateCTM(ctx, 0, rect.size.height);  
  2. CGContextScaleCTM(ctx, 1, -1);  

CTFramesetter是CTFrame的建立工廠,NSAttributedString需要通過CTFrame繪製到介面上,得到CTFramesetter後,建立path(繪製路徑),然後得到CTFrame,最後通過CTFrameDraw方法繪製到介面上。

如果想要計算NSAttributedString所要的size,就需要用到這個API:

CTFramesetterSuggestFrameSizeWithConstraints,用NSString的sizeWithFont算多行時會算不準的,因為在CoreText裡,行間距也是你來控制的。

設定行間距和換行模式都是設定一個屬性:kCTParagraphStyleAttributeName,這個屬性裡面又分為很多子

屬性,其中就包括

  • kCTLineBreakByCharWrapping
  • kCTParagraphStyleSpecifierLineSpacingAdjustment
設定如下:

  1. //段落  
  2.     //line break  
  3. CTParagraphStyleSetting lineBreakMode;  
  4. CTLineBreakMode lineBreak = kCTLineBreakByCharWrapping; //換行模式  
  5. lineBreakMode.spec = kCTParagraphStyleSpecifierLineBreakMode;  
  6. lineBreakMode.value = &lineBreak;  
  7. lineBreakMode.valueSize = sizeof(CTLineBreakMode);  
  8.     //行間距  
  9. CTParagraphStyleSetting LineSpacing;  
  10. CGFloat spacing = 4.0;  //指定間距  
  11. LineSpacing.spec = kCTParagraphStyleSpecifierLineSpacingAdjustment;  
  12. LineSpacing.value = &spacing;  
  13. LineSpacing.valueSize = sizeof(CGFloat);  
  14.   
  15. CTParagraphStyleSetting settings[] = {lineBreakMode,LineSpacing};  
  16. CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(settings, 2);   //第二個參數為settings的長度  
  17. [attributedString addAttribute:(NSString *)kCTParagraphStyleAttributeName  
  18.                          value:(id)paragraphStyle  
  19.                          range:NSMakeRange(0, attributedString.length)];  

-----------------------------------------猥瑣的分界線-----------------------------------------

這並不是唯一的方法,還有另一種替代方案:

  1. CATextLayer *textLayer = [CATextLayer layer];  
  2. textLayer.string = getAttributedString();  
  3. textLayer.frame = CGRectMake(0, CGRectGetMaxY(view.frame), 200, 200);  
  4. [self.view.layer addSublayer:textLayer];  
CATextLayer可以直接支援NSAttributedString!

-----------------------------------------猥瑣的分界線-----------------------------------------


源碼地址-----------------------------------------猥瑣的分界線-----------------------------------------目前發現有一個問題,好像中文全都會被加粗,設定不加粗的字型也沒用,應該是CoreText的bug,已經上報給了apple了。
-----------------------------------------對於cythb兄提出的問題-----------------------------------------
首先表示感謝關注

原文中確有描述不適當的地方,比如:The upper-left corner of the context is (0, 0) 。實際上Quartz2D的座標系統確實在左下角,只是有一些技術在設定它們的graphics context時使用了不同於Quartz的預設座標系統。相對於Quartz來說,這些座標系統是修改的座標系統(modified coordinate system)。


UPDATED在iOS6之後,建立一個AttributedString變成了一件輕鬆的事情,<CoreText/CoreText.h>已經不需要匯入了。如果我要設定字型的顏色,可以直接這樣:

  1. [textAttr addAttribute:NSForegroundColorAttributeName  
  2.                        value:[UIColor redColor]  
  3.                        range:NSMakeRange(0, text.length)]; 


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.