//
//? 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