关于drawInRect: withAttributes: 等新方法的使用

来源:互联网 发布:网易邮箱客户端mac版 编辑:程序博客网 时间:2024/05/18 02:26

新的方法采用的是 attributes,attributes参数需要的是一个数组
我们常用的有几个:

    NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;    NSDictionary* dic = @{NSFontAttributeName:font,NSParagraphStyleAttributeName:paragraphStyle,NSForegroundColorAttributeName:[UIColor lightGrayColor]};

通过设置 NSParagraphStyleAttributeName,我们可以设置string的段落风格,比如 lineBreakMode
NSForegroundColorAttributeName 字体颜色
eg:
原先可以这样写:

CGSize size = [text sizeWithFont:font constrainedToSize:CGSizeMake(300, MAXFLOAT)lineBreakMode:NSLineBreakByCharWrapping];[text drawInRect:CGRectMake(10,10,300, size.height) withFont:font lineBreakMode:NSLineBreakByCharWrapping];

iOS7 之后需要切换新方法,如下:

    NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;    NSDictionary*attribute = @{NSFontAttributeName:font,NSParagraphStyleAttributeName:paragraphStyle};    CGSize size = [text boundingRectWithSize:CGSizeMake(300, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attribute context:nil].size;    [text drawWithRect:CGRectMake(10, 10,300, size.height) options:NSStringDrawingUsesLineFragmentOrigin attributes:attribute context:nil];
0 0