前言
开发中某些情况下,会遇到一些特殊要求,比如需要将一段文本按照固定宽度分割成字符串数组,这里提供一段使用核心文本切割字符串的方法。
Swift代码
import UIKit
extension String {
///根据字体和宽度切割字符串
func separatedLines(with font: UIFont, width: CGFloat) -> [String] {
let attributedString = NSMutableAttributedString(string: self)
attributedString.addAttribute(NSAttributedString.Key(kCTFontAttributeName as String), value: CTFontCreateWithName((font.fontName) as CFString, font.pointSize, nil), range: NSRange(location: 0, length: attributedString.length))
let frameSetter = CTFramesetterCreateWithAttributedString(attributedString)
let path = CGMutablePath()
path.addRect(CGRect(x: 0, y: 0, width: width, height: 100000), transform: .identity)
let frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil)
let lines = CTFrameGetLines(frame)
var linesArray: [String] = []
for line in (lines as Array) {
let lineRef = line as! CTLine
let lineRange: CFRange = CTLineGetStringRange(lineRef)
let range = NSRange(location: lineRange.location, length: lineRange.length)
let lineString = (self as NSString).substring(with: range)
linesArray.append(lineString)
}
return linesArray
}
}
OC代码
#import <UIKit/UIKit.h>
#import "NSString+Separated.h"
#import <CoreText/CoreText.h>
@implementation NSString (Separated)
/**
根据字体和每一行宽度切割字符串
@param font 字体
@param width 宽度
@return 切割后字符串数组
*/
- (NSArray *)separatedLinesWithFont:(UIFont *)font width:(CGFloat)width {
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self];
[attributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)CTFontCreateWithName((__bridge CFStringRef)([font fontName]), [font pointSize], NULL) range:NSMakeRange(0, attributedString.length)];
CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attributedString);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(0, 0, width, 100000));
CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame);
NSMutableArray *linesArray = [[NSMutableArray alloc]init];
for (id line in lines) {
CTLineRef lineRef = (__bridge CTLineRef )line;
CFRange lineRange = CTLineGetStringRange(lineRef);
NSRange range = NSMakeRange(lineRange.location, lineRange.length);
NSString *lineString = [self substringWithRange:range];
[linesArray addObject:lineString];
}
return (NSArray *)linesArray;
}
@end
网友评论