android 根据文本计算行数,ios 获取Text行数和每行显示的内容

该方法主要使用了CoreText中的内容,了解更多CoreText的内容请看CoreText系列

下面是具体代码

- (NSArray *)getLinesArrayOfStringInLabel:(NSString *)string font:(UIFont *)font andLableWidth:(CGFloat)lableWidth{

CTFontRef myFont = CTFontCreateWithName(( CFStringRef)([font fontName]), [font pointSize], NULL);

NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:string];

[attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)myFont range:NSMakeRange(0, attStr.length)];

CFRelease(myFont);

CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString(( CFAttributedStringRef)attStr);

CGMutablePathRef path = CGPathCreateMutable();

CGPathAddRect(path, NULL, CGRectMake(0,0,lableWidth,100000));

CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);

NSArray *lines = ( 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 = [string substringWithRange:range];

CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithFloat:0.0]));

CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithInt:0.0]));

[linesArray addObject:lineString];

}

CGPathRelease(path);

CFRelease( frame );

CFRelease(frameSetter);

return (NSArray *)linesArray;

}

* 返回结果即为包含每行文字的数组,行数即为count数

* 该方法主要是预先的计算出文本在UIlable等控件中的显示情况,从而进行一些其它的后续操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值