您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 利用 Core Text 對文字進行排版

編輯:iOS 相關資訊

Core Text 是 iOS 上強大的文字排版引擎。要使用它,預設專案裡並沒有這個框架,需要手動加入 CoreText.framework。以下幾個關鍵點,是實作自訂文字排版時必須掌握的核心。

幾個必記的排版關鍵

字間距:kCTKernAttributeName
行間距:kCTParagraphStyleSpecifierLineSpacingAdjustment(不建議使用 kCTParagraphStyleSpecifierLineSpacing)
段間距:kCTParagraphStyleSpecifierParagraphSpacing
對齊方式:kCTParagraphStyleSpecifierAlignment

座標翻轉:Core Text 畫出來的文字預設是上下顛倒的,使用前必須翻轉座標系:

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);

換行符差異:Mac 的換行是 \n,而 Windows 是 \r\n。若不先統一,每段結尾都會多出一個空行。解法是先做一次替換:

NSString *myString = [labelString stringByReplacingOccurrencesOfString:@"\r\n" withString:@"\n"];

完整實作:自訂 TextLayoutLabel

下面透過繼承 UILabel,打造一個可自訂字間距與行間距的標籤類。

#import <UIKit/UIKit.h>

@interface TextLayoutLabel : UILabel {
    @private CGFloat characterSpacing_; // 字間距
    @private long linesSpacing_;        // 行間距
}
@property (nonatomic, assign) CGFloat characterSpacing;
@property (nonatomic, assign) long linesSpacing;
@end

#import "TextLayoutLabel.h"
#import <CoreText/CoreText.h>

@implementation TextLayoutLabel
@synthesize characterSpacing = characterSpacing_;
@synthesize linesSpacing = linesSpacing_;

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.characterSpacing = 2.0f;
        self.linesSpacing = 5.0f;
    }
    return self;
}

- (void)setCharacterSpacing:(CGFloat)characterSpacing {
    characterSpacing_ = characterSpacing;
    [self setNeedsDisplay];
}

- (void)setLinesSpacing:(long)linesSpacing {
    linesSpacing_ = linesSpacing;
    [self setNeedsDisplay];
}

- (void)drawTextInRect:(CGRect)requestedRect {
    // 去掉多餘空行
    NSString *labelString = self.text;
    NSString *myString = [labelString stringByReplacingOccurrencesOfString:@"\r\n" withString:@"\n"];

    // 建立可變屬性字串
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:self.text];

    // 設定字體及大小
    CTFontRef helveticaBold = CTFontCreateWithName((CFStringRef)self.font.fontName, self.font.pointSize, NULL);
    [string addAttribute:(id)kCTFontAttributeName value:(id)helveticaBold range:NSMakeRange(0, [string length])];

    // 設定字間距
    if (self.characterSpacing) {
        long number = self.characterSpacing;
        CFNumberRef num = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt8Type, &number);
        [string addAttribute:(id)kCTKernAttributeName value:(id)num range:NSMakeRange(0, [string length])];
        CFRelease(num);
    }

    // 設定文字顏色
    [string addAttribute:(id)kCTForegroundColorAttributeName value:(id)(self.textColor.CGColor) range:NSMakeRange(0, [string length])];

    // 文字對齊方式
    CTTextAlignment alignment = kCTLeftTextAlignment;
    if (self.textAlignment == NSTextAlignmentCenter) {
        alignment = kCTCenterTextAlignment;
    }
    if (self.textAlignment == NSTextAlignmentRight) {
        alignment = kCTRightTextAlignment;
    }
    CTParagraphStyleSetting alignmentStyle;
    alignmentStyle.spec = kCTParagraphStyleSpecifierAlignment;
    alignmentStyle.valueSize = sizeof(alignment);
    alignmentStyle.value = &alignment;

    // 行間距
    CGFloat lineSpace = self.linesSpacing;
    CTParagraphStyleSetting lineSpaceStyle;
    lineSpaceStyle.spec = kCTParagraphStyleSpecifierLineSpacingAdjustment;
    lineSpaceStyle.valueSize = sizeof(lineSpace);
    lineSpaceStyle.value = &lineSpace;

    // 段間距
    CGFloat paragraphSpacing = 5.0;
    CTParagraphStyleSetting paragraphSpaceStyle;
    paragraphSpaceStyle.spec = kCTParagraphStyleSpecifierParagraphSpacing;
    paragraphSpaceStyle.valueSize = sizeof(CGFloat);
    paragraphSpaceStyle.value = &paragraphSpacing;

    // 組裝段落樣式
    CTParagraphStyleSetting settings[] = {alignmentStyle, lineSpaceStyle, paragraphSpaceStyle};
    CTParagraphStyleRef style = CTParagraphStyleCreate(settings, sizeof(settings));
    [string addAttribute:(id)kCTParagraphStyleAttributeName value:(id)style range:NSMakeRange(0, [string length])];

    // 排版
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)string);
    CGMutablePathRef leftColumnPath = CGPathCreateMutable();
    CGPathAddRect(leftColumnPath, NULL, CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height));
    CTFrameRef leftFrame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), leftColumnPath, NULL);

    // 翻轉座標系
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    CGContextTranslateCTM(context, 0, self.bounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    // 畫出文字
    CTFrameDraw(leftFrame, context);

    // 釋放資源
    CGPathRelease(leftColumnPath);
    CFRelease(framesetter);
    CFRelease(helveticaBold);
}
@end

這段程式碼的關鍵流程是:建立 NSMutableAttributedString → 逐一加上字體、字間距、顏色與段落樣式屬性 → 用 CTFramesetter 依據路徑排版成 CTFrame → 翻轉座標系 → CTFrameDraw 繪製。只要掌握這條主線,再靈活調整各項屬性,就能實現高度自訂的文字排版效果。別忘了在 dealloc 或適當時機釋放 Core Foundation 物件,以避免記憶體洩漏。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved