Core Text的使用

關於Core Text

Core Text是先進的,低級別的佈局文本和處理字體的技術。Core Text的API包含在Mac OS X v10.5和IOS 3.2中,能被所有的OS X和IOS環境獲取。

Core Text是關聯Core Graphics框架(Quartz)的低級別文本處理技術。如果你需要直接使用Quartz並描繪一些文本,使用Core Text。例如,你擁有自己的頁面佈局引擎;你還有一些文本;你還知道在哪裏佈局文本;你可以使用Core Text來生成字形並根據所有的排版特徵來互相放置它們,排版特徵包括字距調整,連字,換行,連字符連接,對齊。

Core Text佈局文本

Core Text生成字形(根據字符碼和字體數據)和使用字形運行(glyph runs)互相放置它們。Core Text拆分字形運行成行並聚合行爲多行的框架(例如,段落)。Core Text也提供字形和佈局相關的數據,例如字形位置和行與框架(frames)的測量。它處理字符屬性和段落樣式;段落樣式包含各種標籤樣式和定位。

你可以使用Core Text管理字體

Core Text字體API提供字體,字體集合,字體描述和簡單地獲取字體數據。它提供支持多個主字體,字體變更,字體串聯,字體鏈接。除了Quartz,Core Text也提供加載自己字體到當前進程,也就是說,字體激活。


Core Text概述

Core Text是先進的,低級別的佈局文本和處理字體的技術。Core Text直接和Core Graphics(CG,Quartz)工作;Quartz是高速的圖形渲染引擎;它低級別地處理2維圖形在OS X和IOS平臺上。

Core Text調解文本佈局和高級別字體框架以及Quartz的提供的低級別文本和字體框架。Quartz作用於字形和字形位置。Core Text知道字符怎樣映射到字體和影響樣式,字體度量和其他Quartz渲染文本前的屬性信息。Quartz是在基礎級別的唯一方式進行字形描繪,因爲Core Text提供所有可以被Quartz直接使用的數據形式,這樣可以進行高性能的文本渲染。

多線程:Core Text函數可能涉及多線程同步;客戶端不能修改任何被多條線程共享的參數,例如屬性字符串。

Core Text是基於C語言的,平臺無關的API

在IOS和OS X,Core Text的API幾乎是一樣的,雖然OS X版本提供更豐富的字體管理API,包括可變文本集合。然而,這裏有一些不同在UIKit和APPKit,你在兩個平臺編寫代碼時必須考慮到這個問題。

UIView的UIGraphicsGetCurrentContext函數返回的圖形上下文相對於沒有修改的Quartz圖形上下文是被翻過的(UIView的上下文原點在左上方)。

Core Text使用系統數據類型並儘可能地服務,你可以使用相同的約定在其他核心框架。Core Text使用Core Foundation對象作爲很多輸入和輸出參數,所以你可以使用Core Foundation集合來存儲它們。其他Core Text處理的對象,例如Core Graphics框架提供的CGPath對象。

Core Text對象是C語言的不透明對象類型

很多OS X和IOS下的低級別庫是用C語言編寫的,這樣會比較高速和簡單。當使用Core Text,你使用一組C函數,例如CTFramesetterCreateWithAttributedString和CTFramesetterCreateFrame函數,而不是OC對象和方法。

Core Text不透明類型

Core Text佈局引擎經常使用屬性字符串(CFAttributedStringRef)和圖形路徑(CGPathRef)。屬性字符串封裝了需要展示的字符串和屬性(properties或者attributes);屬性定義字符的樣式,例如字體和顏色。Core Text的排版裝置使用屬性字符串的信息來進行字符到字形的轉換。

圖形路徑定義文本框架的形狀。在OS X v10.7和IOS 3.2之後,路徑可以不爲矩形。

CFAttributedString引用類型,CFAttributedStringRef,它能對象橋接(toll-free bridged)到對應的Foundation框架的NSAttributedString對象。這意味着Core Foundation類型是可轉換的;在函數或者方法調用中使用可橋接的Foundation對象。因此,在方法中看到NSAttributedString * 參數,你可以傳遞CFAttributedStringRef;在函數中看到CFAttributedStringRef參數,你可以傳遞NSAttributedString實例(你可能需要抑制編譯器警告來轉換類型)。你可以應用具體的NSAttributedString子類。

屬性是定義字符串字符樣式特徵的鍵值對,這些字符通過範圍(range)分組並共享相同的屬性。屬性本身被傳遞到屬性字符串並從屬性字符串以CFDictionary對象獲取它。爲了應用樣式到字形運行(CTRun對象),創建CFDictionary對象去保存這個屬性,之後創建屬性字符串,傳遞這個字典作爲參數。或者,你可以應用屬性到已經存在的CFMutableAttributedString對象。雖然CFDictionaryRef和NSDictionary是對象橋接(toll-free bridged),個別存儲在字典的屬性對象可能不是。

Core Text對象在運行時(runtime)形成層次結構。在層級的頂層是framesetter對象(CTFramesetterRef)。以屬性字符串和圖形路徑作爲輸入,framesetter生成一個或者多個文本的框架(CTFrameRef)。每個CTFrame對象代表一個段落。


爲了生成框架,framesetter調用一個typesetter對象(CTTypesetterRef)。當佈局文本到框架,framesetter對它應用段落樣式,它包含對齊,製表符設置,行間距,縮進,換行模式。typesetter轉換屬性字符串的字符到字形並調整這些字形爲填充文本框架的行。

每個CTFrame對象包含段落行對象(CTLine)。每個行對象代表一行文本。一個CTFrame對象可能包含一個單獨的長CTLine對象或者它包含一組行對象。在framesetting操作中,typesetter創建行對象,它像框架對象一樣,可以直接描繪自己到圖形上下文。

每個CTLine對象包含一組字形運行對象(CTRun)。字形運行是一組連續的字形,它們共享相同的屬性和方向。當typesetter從字符字符串,屬性,字體對象創建行對象時,會創建字形運行。這意味着行是由一個或者多個字形運行組成。字形運行能夠描繪自己到圖形上下文,雖然大多數客戶端沒必要直接和字形運行交互。

字體對象

在相對於另外一個字形進行字形佈局和建立當前字體並描繪到圖形上下文, 字體對象提供幫助。Core Text字體不透明類型,CTFont,是一個封裝了很多信息的特殊字體實例。它的引用類型,CTFontRef,是和IOS的UIFont和OS X的NSFont對象進行對象橋接。當你創建CTFont對象,你可以指定(或者使用默認)點大小和轉換矩陣,它給與字體實例指定的特徵。你可以查詢字體對象的很多信息,例如點大小,字符到字形的映射,編碼,字體度量數據等其他信息。字體度量是一組參數,例如ascent,descent, leading,cap height,x-height等。字形數據包括多個參數,例如邊界矩陣和字形前進(glyph advances)。

Core Text的字體對象是不可變的,它可以被多個操作對象和工作隊列或者線程同時使用。這裏有很多方式創建字體對象。最佳的方法是使用字體描述(CTFontCreateWithFontDescriptor)來創建。你可以使用大量便利API。例如,你可以使用字體的附言(PostScript)名稱(CTFontCreateWithName)來創建字體或者Core Graphics字體引用(CTFontCreateWithGraphicsFont)。也可以使用CTFontCreateUIFontForLanguage函數創建本地化應用的用戶界面字體引用。

Core Text字體引用提供複雜,自動的字體替換機制;這個機制叫做級聯。在獲取字體特徵時,它爲丟失的字體選擇適當的字體。字體級聯基於級聯列表;它是一個有序的字體描述數組。系統默認級聯列表是多態的,基於用戶語言設置和當前字體。在字體創建時,字體級聯列表會被指定。通過使用字體描述信息,這個機制根據樣式和匹配的字符來匹配字體。CTFontCreateForString函數使用級聯列表來獲取適當的字體並編碼提供的字符串。爲了指定和獲取字體級聯列表,使用字體對象的kCTFontCascadeListAttribute屬性。

字體描述

字體描述使用CTFontDescriptor不透明類型來代表,它可以通過屬性字典來描述描述字體並且能簡單使用字體匹配來創建字體。你可以使用字體描述來創建字體;你可以提供字體對象來獲取字體描述;你可以改變字體描述並使用它創建新的字體對象。你可以通過字體描述來部分描述一個字體,例如,只是字體族名和權重,之後就可以發現所有匹配的這些內容的系統字體。CTFontDescriptorRef類型能和IOS的UIFontDescriptor以及OS X的NSFontDescriptor進行對象橋接。

並不是處理複雜的轉換矩陣,而是創建一個字體屬性字典作爲CTFontDescriptor對象;這個字典包括附言名稱(PostScript),字體族,樣式,特徵(粗體或者斜體)。你可以使用這個描述來創建CTFont對象。字體描述能被序列化並保存在文檔。


你可以認爲字體描述是對字體系統的查詢。你可以使用一個不完整的說明來創建字體描述,也就是說,在屬性字典使用一個或者幾個值,系統會通過這些可用信息來選擇最適合的字體。例如,如果你使用字體族名的字體描述進行查詢(普通、粗體、斜體、粗斜體)又沒有指定任何特徵將會匹配字體族的所有特徵;你可以指定帶有kCTFontTraitsAttribute和kCTFontTraitBold的特徵字典,獲取的結果會更窄,它只包含指定族名和滿足粗體特徵的字體。CTFontDescriptorCreateMatchingFontDescriptors提供匹配查詢的字體描述列表。

在IOS 6。0之後,可以使用CTFontDescriptorMatchFontDescriptorsWithProgressHandler函數下載和請求各種沒有安裝的字體。字體下載不會永久地安裝字體,系統可能在某些情況下刪除它們。可用下載的字體被列在IOS6:和IOS7:字體列表的“額外信息”。

字體集合

字體集合會組合一組字體描述爲單獨的對象。字體集合使用CTFontCollection不透明類型。字體集合提供字體遍歷,獲取全局和自定義字體集合以及字體描述集合的功能。你可以調用CTFontCollectionCreateFromAvailableFonts創建所有可用的字體的集合;你可以使用這個集合獲取所有子集的字體描述數組。


通用文本佈局操作

佈局段落

其中一個最通用的排版操作是在任意矩形區域中佈局多行段落。Core Text讓這種操作變得簡單,只需要幾行的Core Text代碼。爲了排版段落,你需要一個圖形上下文進行繪製,文本佈局區域的矩形路徑,屬性字符串。

// Initialize a graphics context in iOS.
CGContextRef context = UIGraphicsGetCurrentContext();
 
// Flip the context coordinates, in iOS only.
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
 
// Initializing a graphic context in OS X is different:
// CGContextRef context =
//     (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
 
// Set the text matrix.
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
 
// Create a path which bounds the area where you will be drawing text.
// The path need not be rectangular.
CGMutablePathRef path = CGPathCreateMutable();
 
// In this simple example, initialize a rectangular path.
CGRect bounds = CGRectMake(10.0, 10.0, 200.0, 200.0);
CGPathAddRect(path, NULL, bounds );
 
// Initialize a string.
CFStringRef textString = CFSTR("Hello, World! I know nothing in the world that has as much power as a word. Sometimes I write one, and I look at it, until it begins to shine.");
 
// Create a mutable attributed string with a max length of 0.
// The max length is a hint as to how much internal storage to reserve.
// 0 means no hint.
CFMutableAttributedStringRef attrString =
         CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
 
// Copy the textString into the newly created attrString
CFAttributedStringReplaceString (attrString, CFRangeMake(0, 0),
         textString);
 
// Create a color that will be added as an attribute to the attrString.
CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat components[] = { 1.0, 0.0, 0.0, 0.8 };
CGColorRef red = CGColorCreate(rgbColorSpace, components);
CGColorSpaceRelease(rgbColorSpace);
 
// Set the color of the first 12 chars to red.
CFAttributedStringSetAttribute(attrString, CFRangeMake(0, 12),
         kCTForegroundColorAttributeName, red);
 
// Create the framesetter with the attributed string.
CTFramesetterRef framesetter =
         CTFramesetterCreateWithAttributedString(attrString);
CFRelease(attrString);
 
// Create a frame.
CTFrameRef frame = CTFramesetterCreateFrame(framesetter,
          CFRangeMake(0, 0), path, NULL);
 
// Draw the specified frame in the given context.
CTFrameDraw(frame, context);
 
// Release the objects we used.
CFRelease(frame);
CFRelease(path);
CFRelease(framesetter);
簡單的文本標籤

另一個通用的排版操作就是描繪單行文本就像使用圖形界面的標籤(label)。在Core Text,只需要2行代碼:使用CFAttributedString創建行對象和描繪行對象到圖形上下文。

下面的代碼是在drawRect: 方法中執行,它省略文本字符串,字體,圖形上下文的創建。

CFStringRef string; CTFontRef font; CGContextRef context;
// Initialize the string, font, and context
 
CFStringRef keys[] = { kCTFontAttributeName };
CFTypeRef values[] = { font };
 
CFDictionaryRef attributes =
    CFDictionaryCreate(kCFAllocatorDefault, (const void**)&keys,
        (const void**)&values, sizeof(keys) / sizeof(keys[0]),
        &kCFTypeDictionaryKeyCallBacks,
        &kCFTypeDictionaryValueCallBacks);
 
CFAttributedStringRef attrString =
    CFAttributedStringCreate(kCFAllocatorDefault, string, attributes);
CFRelease(string);
CFRelease(attributes);
 
CTLineRef line = CTLineCreateWithAttributedString(attrString);
 
// Set text position and draw the line into the graphics context
CGContextSetTextPosition(context, 10.0, 10.0);
CTLineDraw(line, context);
CFRelease(line);
柱狀佈局

佈局多列的文本是另一通用排版操作。嚴格地講,Core Text本身只能一次佈局一列而且不會計算列的大小或者位置。你需要做這些操作在調用Core Text佈局文本到你計算的區域。在下面的例子中,Core Text,除了佈局每一列的文本還要提供每一列的子文本。

下面的createColumnsWithColumnCount: 方法接收列數參數並返回一組路徑,每個路徑代表一列。

之後的例子是實現在drawRect: 方法,它會調用createColumnsWithColumnCount方法。

- (CFArrayRef)createColumnsWithColumnCount:(int)columnCount
{
    int column;
 
    CGRect* columnRects = (CGRect*)calloc(columnCount, sizeof(*columnRects));
    // Set the first column to cover the entire view.
    columnRects[0] = self.bounds;
 
    // Divide the columns equally across the frame's width.
    CGFloat columnWidth = CGRectGetWidth(self.bounds) / columnCount;
    for (column = 0; column < columnCount - 1; column++) {
        CGRectDivide(columnRects[column], &columnRects[column],
                     &columnRects[column + 1], columnWidth, CGRectMinXEdge);
    }
 
   // Inset all columns by a few pixels of margin.
    for (column = 0; column < columnCount; column++) {
        columnRects[column] = CGRectInset(columnRects[column], 8.0, 15.0);
    }
 
    // Create an array of layout paths, one for each column.
    CFMutableArrayRef array =
                     CFArrayCreateMutable(kCFAllocatorDefault,
                                  columnCount, &kCFTypeArrayCallBacks);
 
    for (column = 0; column < columnCount; column++) {
        CGMutablePathRef path = CGPathCreateMutable();
        CGPathAddRect(path, NULL, columnRects[column]);
        CFArrayInsertValueAtIndex(array, column, path);
        CFRelease(path);
    }
    free(columnRects);
    return array;
}
// Override drawRect: to draw the attributed string into columns.
// (In OS X, the drawRect: method of NSView takes an NSRect parameter,
//  but that parameter is not used in this listing.)
- (void)drawRect:(CGRect)rect
{
    // Initialize a graphics context in iOS.
    CGContextRef context = UIGraphicsGetCurrentContext();
 
    // Flip the context coordinates in iOS only.
    CGContextTranslateCTM(context, 0, self.bounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
 
    // Initializing a graphic context in OS X is different:
    // CGContextRef context =
    //     (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
 
    // Set the text matrix.
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
 
    // Create the framesetter with the attributed string.
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(
                                      (CFAttributedStringRef)self.attributedString);
 
    // Call createColumnsWithColumnCount function to create an array of
    // three paths (columns).
    CFArrayRef columnPaths = [self createColumnsWithColumnCount:3];
 
    CFIndex pathCount = CFArrayGetCount(columnPaths);
    CFIndex startIndex = 0;
    int column;
 
    // Create a frame for each column (path).
    for (column = 0; column < pathCount; column++) {
        // Get the path for this column.
        CGPathRef path = (CGPathRef)CFArrayGetValueAtIndex(columnPaths, column);
 
        // Create a frame for this column and draw it.
        CTFrameRef frame = CTFramesetterCreateFrame(
                             framesetter, CFRangeMake(startIndex, 0), path, NULL);
        CTFrameDraw(frame, context);
 
        // Start the next frame at the first character not visible in this frame.
        CFRange frameRange = CTFrameGetVisibleStringRange(frame);
        startIndex += frameRange.length;
        CFRelease(frame);
 
    }
    CFRelease(columnPaths);
    CFRelease(framesetter);
 
}
手動換行

在Core Text,你通常不需要手動換行除非你有一個特殊的連字符處理或者相似的請求。framesetter會自動執行換行。另外,Core Text允許你明確指定哪一行文本換行。這個例子展示在描繪前怎樣居中行。

這個例子在drawRect: 方法中。

double width; CGContextRef context; CGPoint textPosition; CFAttributedStringRef attrString;
// Initialize those variables.
 
// Create a typesetter using the attributed string.
CTTypesetterRef typesetter = CTTypesetterCreateWithAttributedString(attrString);
 
// Find a break for line from the beginning of the string to the given width.
CFIndex start = 0;
CFIndex count = CTTypesetterSuggestLineBreak(typesetter, start, width);
 
// Use the returned character count (to the break) to create the line.
CTLineRef line = CTTypesetterCreateLine(typesetter, CFRangeMake(start, count));
 
// Get the offset needed to center the line.
float flush = 0.5; // centered
double penOffset = CTLineGetPenOffsetForFlush(line, flush, width);
 
// Move the given text drawing position by the calculated offset and draw the line.
CGContextSetTextPosition(context, textPosition.x + penOffset, textPosition.y);
CTLineDraw(line, context);
 
// Move the index beyond the line break.
start += count;
應用段落樣式
NSAttributedString* applyParaStyle(
                CFStringRef fontName , CGFloat pointSize,
                NSString *plainText, CGFloat lineSpaceInc){
 
    // Create the font so we can determine its height.
    CTFontRef font = CTFontCreateWithName(fontName, pointSize, NULL);
 
    // Set the lineSpacing.
    CGFloat lineSpacing = (CTFontGetLeading(font) + lineSpaceInc) * 2;
 
    // Create the paragraph style settings.
    CTParagraphStyleSetting setting;
 
    setting.spec = kCTParagraphStyleSpecifierLineSpacing;
    setting.valueSize = sizeof(CGFloat);
    setting.value = &lineSpacing;
 
    CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(&setting, 1);
 
    // Add the paragraph style to the dictionary.
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                               (__bridge id)font, (id)kCTFontNameAttribute,
                               (__bridge id)paragraphStyle,
                               (id)kCTParagraphStyleAttributeName, nil];
    CFRelease(font);
    CFRelease(paragraphStyle);
 
    // Apply the paragraph style to the string to created the attributed string.
    NSAttributedString* attrString = [[NSAttributedString alloc]
                               initWithString:(NSString*)plainText
                               attributes:attributes];
 
    return attrString;
}

描繪段落樣式

- (void)drawRect:(CGRect)rect {
    // Initialize a graphics context in iOS.
    CGContextRef context = UIGraphicsGetCurrentContext();
 
    // Flip the context coordinates in iOS only.
    CGContextTranslateCTM(context, 0, self.bounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
 
    // Set the text matrix.
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
 
    CFStringRef fontName = CFSTR("Didot Italic");
    CGFloat pointSize = 24.0;
 
    CFStringRef string = CFSTR("Hello, World! I know nothing in the world that has
                                   as much power as a word. Sometimes I write one,
                                   and I look at it, until it begins to shine.");
 
    // Apply the paragraph style.
    NSAttributedString* attrString = applyParaStyle(fontName, pointSize, string, 50.0);
 
    // Put the attributed string with applied paragraph style into a framesetter.
    CTFramesetterRef framesetter =
             CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attrString);
 
    // Create a path to fill the View.
    CGPathRef path = CGPathCreateWithRect(rect, NULL);
 
    // Create a frame in which to draw.
    CTFrameRef frame = CTFramesetterCreateFrame(
                                    framesetter, CFRangeMake(0, 0), path, NULL);
 
    // Draw the frame.
    CTFrameDraw(frame, context);
    CFRelease(frame);
    CGPathRelease(path);
    CFRelease(framesetter);
}
在非矩形區域展示文本
// Create a path in the shape of a donut.
static void AddSquashedDonutPath(CGMutablePathRef path,
              const CGAffineTransform *m, CGRect rect)
{
    CGFloat width = CGRectGetWidth(rect);
    CGFloat height = CGRectGetHeight(rect);
 
    CGFloat radiusH = width / 3.0;
    CGFloat radiusV = height / 3.0;
 
    CGPathMoveToPoint( path, m, rect.origin.x, rect.origin.y + height - radiusV);
    CGPathAddQuadCurveToPoint( path, m, rect.origin.x, rect.origin.y + height,
                               rect.origin.x + radiusH, rect.origin.y + height);
    CGPathAddLineToPoint( path, m, rect.origin.x + width - radiusH,
                               rect.origin.y + height);
    CGPathAddQuadCurveToPoint( path, m, rect.origin.x + width,
                               rect.origin.y + height,
                               rect.origin.x + width,
                               rect.origin.y + height - radiusV);
    CGPathAddLineToPoint( path, m, rect.origin.x + width,
                               rect.origin.y + radiusV);
    CGPathAddQuadCurveToPoint( path, m, rect.origin.x + width, rect.origin.y,
                               rect.origin.x + width - radiusH, rect.origin.y);
    CGPathAddLineToPoint( path, m, rect.origin.x + radiusH, rect.origin.y);
    CGPathAddQuadCurveToPoint( path, m, rect.origin.x, rect.origin.y,
                               rect.origin.x, rect.origin.y + radiusV);
    CGPathCloseSubpath( path);
 
    CGPathAddEllipseInRect( path, m,
                            CGRectMake( rect.origin.x + width / 2.0 - width / 5.0,
                            rect.origin.y + height / 2.0 - height / 5.0,
                            width / 5.0 * 2.0, height / 5.0 * 2.0));
}
 
// Generate the path outside of the drawRect call so the path is calculated only once.
- (NSArray *)paths
{
    CGMutablePathRef path = CGPathCreateMutable();
    CGRect bounds = self.bounds;
    bounds = CGRectInset(bounds, 10.0, 10.0);
    AddSquashedDonutPath(path, NULL, bounds);
 
    NSMutableArray *result =
              [NSMutableArray arrayWithObject:CFBridgingRelease(path)];
    return result;
}
 
- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
 
    // Initialize a graphics context in iOS.
    CGContextRef context = UIGraphicsGetCurrentContext();
 
    // Flip the context coordinates in iOS only.
    CGContextTranslateCTM(context, 0, self.bounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
 
    // Set the text matrix.
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
 
    // Initialize an attributed string.
    CFStringRef textString = CFSTR("Hello, World! I know nothing in the world that
    has as much power as a word. Sometimes I write one, and I look at it,
    until it begins to shine.");
 
    // Create a mutable attributed string.
     CFMutableAttributedStringRef attrString =
                CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
 
    // Copy the textString into the newly created attrString.
    CFAttributedStringReplaceString (attrString, CFRangeMake(0, 0), textString);
 
    // Create a color that will be added as an attribute to the attrString.
    CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
    CGFloat components[] = { 1.0, 0.0, 0.0, 0.8 };
    CGColorRef red = CGColorCreate(rgbColorSpace, components);
    CGColorSpaceRelease(rgbColorSpace);
 
    // Set the color of the first 13 chars to red.
    CFAttributedStringSetAttribute(attrString, CFRangeMake(0, 13),
                                     kCTForegroundColorAttributeName, red);
 
    // Create the framesetter with the attributed string.
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attrString);
 
    // Create the array of paths in which to draw the text.
    NSArray *paths = [self paths];
 
    CFIndex startIndex = 0;
 
    // In OS X, use NSColor instead of UIColor.
    #define GREEN_COLOR [UIColor greenColor]
    #define YELLOW_COLOR [UIColor yellowColor]
    #define BLACK_COLOR [UIColor blackColor]
 
    // For each path in the array of paths...
    for (id object in paths) {
        CGPathRef path = (__bridge CGPathRef)object;
 
        // Set the background of the path to yellow.
        CGContextSetFillColorWithColor(context, [YELLOW_COLOR CGColor]);
 
        CGContextAddPath(context, path);
        CGContextFillPath(context);
 
        CGContextDrawPath(context, kCGPathStroke);
 
        // Create a frame for this path and draw the text.
        CTFrameRef frame = CTFramesetterCreateFrame(framesetter,
                                         CFRangeMake(startIndex, 0), path, NULL);
        CTFrameDraw(frame, context);
 
        // Start the next frame at the first character not visible in this frame.
        CFRange frameRange = CTFrameGetVisibleStringRange(frame);
        startIndex += frameRange.length;
        CFRelease(frame);
}
 
CFRelease(attrString);
CFRelease(framesetter);
}

通用字體操作

創建字體描述

指定PostScript字體名稱和點大小來創建字體描述。

CTFontDescriptorRef CreateFontDescriptorFromName(CFStringRef postScriptName,
                                                  CGFloat size)
{
    return CTFontDescriptorCreateWithNameAndSize(postScriptName, size);
}

使用字體族名和字體特徵來創建字體描述。

NSString* familyName = @"Papyrus";
CTFontSymbolicTraits symbolicTraits = kCTFontTraitCondensed;
CGFloat size = 24.0;
 
NSMutableDictionary* attributes = [NSMutableDictionary dictionary];
[attributes setObject:familyName forKey:(id)kCTFontFamilyNameAttribute];
 
// The attributes dictionary contains another dictionary, the traits dictionary,
// which in this example specifies only the symbolic traits.
NSMutableDictionary* traits = [NSMutableDictionary dictionary];
[traits setObject:[NSNumber numberWithUnsignedInt:symbolicTraits]
                                           forKey:(id)kCTFontSymbolicTrait];
 
[attributes setObject:traits forKey:(id)kCTFontTraitsAttribute];
[attributes setObject:[NSNumber numberWithFloat:size]
                                         forKey:(id)kCTFontSizeAttribute];
 
CTFontDescriptorRef descriptor =
             CTFontDescriptorCreateWithAttributes((CFDictionaryRef)attributes);
CFRelease(descriptor);
使用字體描述創建字體
NSDictionary *fontAttributes =
                  [NSDictionary dictionaryWithObjectsAndKeys:
                          @"Courier", (NSString *)kCTFontFamilyNameAttribute,
                          @"Bold", (NSString *)kCTFontStyleNameAttribute,
                          [NSNumber numberWithFloat:16.0],
                          (NSString *)kCTFontSizeAttribute,
                          nil];
// Create a descriptor.
CTFontDescriptorRef descriptor =
          CTFontDescriptorCreateWithAttributes((CFDictionaryRef)fontAttributes);
 
// Create a font using the descriptor.
CTFontRef font = CTFontCreateWithFontDescriptor(descriptor, 0.0, NULL);
CFRelease(descriptor);
創建相關字體

你可以轉換存在的字體爲相關或者相似的字體。

CTFontRef CreateBoldFont(CTFontRef font, Boolean makeBold)
{
    CTFontSymbolicTraits desiredTrait = 0;
    CTFontSymbolicTraits traitMask;
 
    // If requesting that the font be bold, set the desired trait
    // to be bold.
    if (makeBold) desiredTrait = kCTFontBoldTrait;
 
    // Mask off the bold trait to indicate that it is the only trait
    // to be modified. As CTFontSymbolicTraits is a bit field,
    // could change multiple traits if desired.
    traitMask = kCTFontBoldTrait;
 
    // Create a copy of the original font with the masked trait set to the
    // desired value. If the font family does not have the appropriate style,
    // returns NULL.
 
    return CTFontCreateCopyWithSymbolicTraits(font, 0.0, NULL, desiredTrait, traitMask);
}
CTFontRef CreateFontConvertedToFamily(CTFontRef font, CFStringRef family)
{
    // Create a copy of the original font with the new family. This call
    // attempts to preserve traits, and may return NULL if that is not possible.
    // Pass in 0.0 and NULL for size and matrix to preserve the values from
    // the original font.
 
    return CTFontCreateCopyWithFamily(font, 0.0, NULL, family);
}
序列化字體
CFDataRef CreateFlattenedFontData(CTFontRef font)
{
    CFDataRef           result = NULL;
    CTFontDescriptorRef descriptor;
    CFDictionaryRef     attributes;
 
    // Get the font descriptor for the font.
    descriptor = CTFontCopyFontDescriptor(font);
 
    if (descriptor != NULL) {
        // Get the font attributes from the descriptor. This should be enough
        // information to recreate the descriptor and the font later.
        attributes = CTFontDescriptorCopyAttributes(descriptor);
 
        if (attributes != NULL) {
            // If attributes are a valid property list, directly flatten
            // the property list. Otherwise we may need to analyze the attributes
            // and remove or manually convert them to serializable forms.
            // This is left as an exercise for the reader.
           if (CFPropertyListIsValid(attributes, kCFPropertyListXMLFormat_v1_0)) {
                result = CFPropertyListCreateXMLData(kCFAllocatorDefault, attributes);
            }
        }
    }
    return result;
}
使用序列化數據創建字體
CTFontRef CreateFontFromFlattenedFontData(CFDataRef iData)
{
    CTFontRef           font = NULL;
    CFDictionaryRef     attributes;
    CTFontDescriptorRef descriptor;
 
    // Create our font attributes from the property list.
    // For simplicity, this example creates an immutable object.
    // If you needed to massage or convert certain attributes
    // from their serializable form to the Core Text usable form,
    // do it here.
    attributes =
          (CFDictionaryRef)CFPropertyListCreateFromXMLData(
                               kCFAllocatorDefault,
                               iData, kCFPropertyListImmutable, NULL);
    if (attributes != NULL) {
        // Create the font descriptor from the attributes.
        descriptor = CTFontDescriptorCreateWithAttributes(attributes);
        if (descriptor != NULL) {
            // Create the font from the font descriptor. This sample uses
            // 0.0 and NULL for the size and matrix parameters. This
            // causes the font to be created with the size and/or matrix
            // that exist in the descriptor, if present. Otherwise default
            // values are used.
            font = CTFontCreateWithFontDescriptor(descriptor, 0.0, NULL);
        }
    }
    return font;
}
改變字距調整
連字和字距調整默認是激活的。你可以設置kCTKernAttributeName爲0來失效它。
 // Set the color of the first 13 characters to red
 // using a previously defined red CGColor object.
 CFAttributedStringSetAttribute(attrString, CFRangeMake(0, 13),
                                      kCTForegroundColorAttributeName, red);
 
 // Set kerning between the first 18 chars to be 20
 CGFloat otherNum = 20;
 CFNumberRef otherCFNum = CFNumberCreate(NULL, kCFNumberCGFloatType, &otherNum);
 CFAttributedStringSetAttribute(attrString, CFRangeMake(0,18),
                                           kCTKernAttributeName, otherCFNum);
獲取字符的字形
void GetGlyphsForCharacters(CTFontRef font, CFStringRef string)
{
    // Get the string length.
    CFIndex count = CFStringGetLength(string);
 
    // Allocate our buffers for characters and glyphs.
    UniChar *characters = (UniChar *)malloc(sizeof(UniChar) * count);
    CGGlyph *glyphs = (CGGlyph *)malloc(sizeof(CGGlyph) * count);
 
    // Get the characters from the string.
    CFStringGetCharacters(string, CFRangeMake(0, count), characters);
 
    // Get the glyphs for the characters.
    CTFontGetGlyphsForCharacters(font, characters, glyphs, count);
 
    // Do something with the glyphs here. Characters not mapped by this font will be zero.
    // ...
 
    // Free the buffers
    free(characters);
    free(glyphs);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章