CoreText編程指南(常用字體操作)

Common Font Operations(常用字體操作)

這一章描述了一個(gè)常用的字體處理操作,并展示了怎么用CoreText代碼來實(shí)現(xiàn)它們良风。這些操作在iOS和OS X中是一樣的升酣。本章包含下面的操作列表:

  • 創(chuàng)建一個(gè)字體描述符
  • 從字體描述符創(chuàng)建一個(gè)字體
  • 創(chuàng)建相關(guān)的字體
  • 解析字體
  • 用字體解析數(shù)據(jù)創(chuàng)建一個(gè)字體
  • 調(diào)整字距
  • 從字符中獲得符號(hào)

Creating Font Descriptors(創(chuàng)建字體描述符)

清單3-1中示例函數(shù)用PostScrpt font name和字號(hào)作為參數(shù)創(chuàng)建一個(gè)字體描述符。

Listing 3-1 Creating a font descriptor from a name and point size

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

清單3-2中的示例函數(shù)從font family namefont traits創(chuàng)建一個(gè)字體描述符。

Listing 3-2 Creating a font descriptor from a family and traits

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

Creating a Font from a Font Descriptor(從字體描述符創(chuàng)建字體)

清單3-3展示了怎么創(chuàng)建一個(gè)字體描述符并用它創(chuàng)建一個(gè)字體雨效。當(dāng)你調(diào)用CTFontCreateWithFontDescriptor時(shí),你通常傳NULLmatrix參數(shù)來制定一個(gè)默認(rèn)(identity)的矩陣废赞。CTFontCreateWithFontDescriptorsizematrix(第二個(gè)和第三個(gè))參數(shù)會(huì)覆蓋制定的字體描述符中指定的值徽龟,除非(字體描述符中)他們沒有被指定(size為0,matrixNULL)唉地。

Listing 3-3 Creating a font from a font 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);

Creating Related Fonts(創(chuàng)建相關(guān)字體)

把一個(gè)已經(jīng)存在的字體轉(zhuǎn)化成一個(gè)相關(guān)或類似的字體經(jīng)常是有用的据悔。清單3-4中的示例函數(shù)展示了怎么根據(jù)函數(shù)調(diào)用時(shí)傳的Boolean參數(shù)的值,來生成一個(gè)粗體或者非粗體的字體耘沼。如果當(dāng)前字體family沒有需要的樣式极颓,這個(gè)函數(shù)返回NULL

Listing 3-4 Changing traits of a font

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

清單3-8中的示例函數(shù)把所給的字體轉(zhuǎn)換成另一個(gè)字體family中相似的字體耕拷,盡可能的保留特征讼昆。它可能返回NULLsize參數(shù)傳0骚烧,matrix參數(shù)傳NULL來保留原始字體的尺寸浸赫。

Listing 3-5 Converting a font to another family

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

Serializing a Font(解析字體)

清單3-6中的示例函數(shù)展示了怎么解析字體并創(chuàng)建一個(gè)可以嵌入到文檔的XML數(shù)據(jù)。還有一種選擇赃绊,而且是比較好的既峡,可以用NSArchiver。這只是完成任務(wù)的一種方法碧查,但是它保留了以后重新創(chuàng)建字體所需的所有數(shù)據(jù)运敢。

Listing 3-6 Serializing a font

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;
}

Creating a Font from Serialized Data(從解析數(shù)據(jù)創(chuàng)建字體)

清單3-7中的示例函數(shù)展示了怎么從XML數(shù)據(jù)創(chuàng)建一個(gè)字體引用。它展示了怎么解壓出字體屬性并用那些屬性創(chuàng)建字體忠售。

Listing 3-7 Creating a font from serialized data

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;
}

Changing Kerning(調(diào)整字間距)

聯(lián)結(jié)和字間距是默認(rèn)開啟的传惠。通過設(shè)置kCTKernAttributeName屬性為0來關(guān)閉它。清單3-8在前幾個(gè)字符繪制的時(shí)候把字間距設(shè)置成一個(gè)大的數(shù)字稻扬。

Listing 3-8 Setting kerning

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

Getting Glyphs for Characters(從字符中獲取符號(hào))

清單3-9展示了怎么用一個(gè)字體從stringcharacters中獲取glyphs卦方。大部分時(shí)間有應(yīng)該只從CTLine對(duì)象中獲取這些信息,因?yàn)檎麄€(gè)string可能不止用了一個(gè)字體泰佳。而且盼砍,對(duì)于復(fù)雜的文本簡(jiǎn)單的character-to-glyph mapping不會(huì)得到正確的外觀尘吗。這個(gè)簡(jiǎn)單的glyph mapping可能在你嘗試用一個(gè)字體顯示特定Unicode字符時(shí)是合適的。

Listing 3-9 Getting glyphs for characters

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);
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末浇坐,一起剝皮案震驚了整個(gè)濱河市睬捶,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌近刘,老刑警劉巖擒贸,帶你破解...
    沈念sama閱讀 221,695評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異跌宛,居然都是意外死亡酗宋,警方通過查閱死者的電腦和手機(jī)积仗,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,569評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門疆拘,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人寂曹,你說我怎么就攤上這事哎迄。” “怎么了隆圆?”我有些...
    開封第一講書人閱讀 168,130評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵漱挚,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我渺氧,道長(zhǎng)旨涝,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,648評(píng)論 1 297
  • 正文 為了忘掉前任侣背,我火速辦了婚禮白华,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘贩耐。我一直安慰自己弧腥,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,655評(píng)論 6 397
  • 文/花漫 我一把揭開白布潮太。 她就那樣靜靜地躺著管搪,像睡著了一般。 火紅的嫁衣襯著肌膚如雪铡买。 梳的紋絲不亂的頭發(fā)上更鲁,一...
    開封第一講書人閱讀 52,268評(píng)論 1 309
  • 那天,我揣著相機(jī)與錄音奇钞,去河邊找鬼澡为。 笑死,一個(gè)胖子當(dāng)著我的面吹牛蛇券,可吹牛的內(nèi)容都是我干的缀壤。 我是一名探鬼主播樊拓,決...
    沈念sama閱讀 40,835評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼塘慕!你這毒婦竟也來了筋夏?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,740評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤图呢,失蹤者是張志新(化名)和其女友劉穎条篷,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體蛤织,經(jīng)...
    沈念sama閱讀 46,286評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡赴叹,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,375評(píng)論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了指蚜。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片乞巧。...
    茶點(diǎn)故事閱讀 40,505評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖摊鸡,靈堂內(nèi)的尸體忽然破棺而出绽媒,到底是詐尸還是另有隱情,我是刑警寧澤免猾,帶...
    沈念sama閱讀 36,185評(píng)論 5 350
  • 正文 年R本政府宣布是辕,位于F島的核電站,受9級(jí)特大地震影響猎提,放射性物質(zhì)發(fā)生泄漏获三。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,873評(píng)論 3 333
  • 文/蒙蒙 一锨苏、第九天 我趴在偏房一處隱蔽的房頂上張望疙教。 院中可真熱鬧,春花似錦蚓炬、人聲如沸松逊。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,357評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽经宏。三九已至,卻和暖如春驯击,著一層夾襖步出監(jiān)牢的瞬間烁兰,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,466評(píng)論 1 272
  • 我被黑心中介騙來泰國(guó)打工徊都, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留沪斟,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,921評(píng)論 3 376
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像主之,于是被迫代替她去往敵國(guó)和親择吊。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,515評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容