iOS开发之 CoreText 根据指定区域大小给文本进行分页

根据指定页大小给文本(NSAttributedString)进行分页

/**
 * @param attributedString 需要进行分页的富文本
 * @param bounds 每页大小
 */
- (NSArray *)automaticPagingWithAttributedString:(NSAttributedString *)attributedString withBounds:(CGRect)bounds{
    NSMutableArray *pagingStrings = [NSMutableArray arrayWithCapacity:0];
    if (attributedString) {
        NSMutableAttributedString *attrString = [attributedString mutableCopy];
        while (attrString.length > 0) {
            @autoreleasepool {
                CGPathRef path = CGPathCreateWithRect(CGRectMake(0, 0, bounds.size.width, bounds.size.height), NULL);
                CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attrString);
                CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, attrString.length), path, NULL);
                CFRange visibleStringRange = CTFrameGetVisibleStringRange(frame);
                [pagingStrings addObject:[attrString attributedSubstringFromRange:NSMakeRange(0, visibleStringRange.length)]];
                [attrString deleteCharactersInRange:NSMakeRange(0, visibleStringRange.length)];
                CGPathRelease(path);
            }
        }
    }
    return pagingStrings;
}
或者使用
@interface NSAttributedString(XCPagingAttributedString)

/**
 * @param bounds 每页大小
 */
- (NSArray *)automaticPagingWithBounds:(CGRect)bounds;

@end

@implementation NSAttributedString(XCPagingAttributedString)


+ (void)load{
    Class class = [super class];
    SEL select = @selector(automaticPagingWithBounds:);
    Method method = class_getInstanceMethod(class, select);
    IMP implementation = method_getImplementation(method);
    class_addMethod(class, select, implementation, method_getTypeEncoding(method));
}

/**
 * @param bounds 每页大小
 */
- (NSArray *)automaticPagingWithBounds:(CGRect)bounds{
    NSMutableArray *pagingStrings = [NSMutableArray arrayWithCapacity:0];
    NSMutableAttributedString *attrString = [self mutableCopy];
    while (attrString.length > 0) {
        @autoreleasepool {
            CGPathRef path = CGPathCreateWithRect(CGRectMake(0, 0, bounds.size.width, bounds.size.height), NULL);
            CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attrString);
            CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, attrString.length), path, NULL);
            CFRange visibleStringRange = CTFrameGetVisibleStringRange(frame);
            [pagingStrings addObject:[attrString attributedSubstringFromRange:NSMakeRange(0, visibleStringRange.length)]];
            [attrString deleteCharactersInRange:NSMakeRange(0, visibleStringRange.length)];
            CGPathRelease(path);
        }
    }
    return pagingStrings;
}
@end

你可能感兴趣的:(iOS开发之 CoreText 根据指定区域大小给文本进行分页)