iOS 字符串按寬度截取

//

//? ViewController.m

//? TestSubText

//

//? Created by zhangzifei on 2019/9/20.

//? Copyright ? 2019 KYE. All rights reserved.

//

#import "ViewController.h"

#import

@interface ViewController ()

@end

@implementationViewController

- (void)viewDidLoad {

? ? [super viewDidLoad];

? ? // Do any additional setup after loading the view.

? ? UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 300, 30)];

? ? label.text = @"創建存結構CoreTextData儲B結構CTImgData";

? ? label.backgroundColor = [UIColor redColor];

? ? [self.viewaddSubview:label];


? ? CGFloattextWidth = [selfgetTextWidthWithStr:label.text];



? ? if(textWidth >300) {

? ? ? ? label.text= [selfgetVisibleStringWithWidth:300font:label.fontstr:label.text];

? ? }

}

- (CGFloat)getTextWidthWithStr:(NSString*)str {


? ? NSString*countStr = str;

? ? NSMutableParagraphStyle *p = [[NSMutableParagraphStyle alloc] init];

? ? p.lineBreakMode = NSLineBreakByCharWrapping;

? ? CGFloat countWidht = [countStr boundingRectWithSize:CGSizeMake(999., 25.) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17.f], NSParagraphStyleAttributeName:p} context:nil].size.width;

? ? returncountWidht;

}

- (NSString*)getVisibleStringWithWidth:(CGFloat)width font:(UIFont*)font str:(NSString*)str {


? ? NSMutableParagraphStyle *p = [[NSMutableParagraphStyle alloc] init];

? ? p.lineBreakMode = NSLineBreakByCharWrapping;


? ? NSAttributedString *namesAtt = [[NSAttributedString alloc] initWithString:str attributes:@{NSFontAttributeName:font, NSParagraphStyleAttributeName:p}];


? ? CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)namesAtt);


? ? UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, width, 25.)];

? ? CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, str.length), path.CGPath, NULL);


? ? CFRange range = CTFrameGetVisibleStringRange(frame);

? ? CFRelease(framesetter);

? ? CFRelease(frame);


? ? return [str substringWithRange:NSMakeRange(range.location, range.length)];

}

@end

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容