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

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

/**
 * @param attributedString 需要进行分页的富文本
 * @param bounds 每页大小
 */
- (NSArray<NSAttributedString *> *)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<NSAttributedString *> *)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<NSAttributedString *> *)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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。