美文网首页
iOS 字符串按宽度截取

iOS 字符串按宽度截取

作者: 无名指的情怀 | 来源:发表于2019-09-26 11:06 被阅读0次

    //

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

    相关文章

      网友评论

          本文标题:iOS 字符串按宽度截取

          本文链接:https://www.haomeiwen.com/subject/skujuctx.html