+(CGSize)getAttributedTextSize:(NSString *)text
{
//先把普通的字符串text转化生成Attributed类型的字符串
NSMutableAttributedString * attStr = [[NSMutableAttributedString alloc]initWithString:text];
NSString * zhengze = @\[[a-zA-Z0-
9
\u4e00-\u9fa5]+\];
NSError * error;
NSRegularExpression * re = [NSRegularExpression regularExpressionWithPattern:zhengze options:NSRegularExpressionCaseInsensitive error:&error];
if
(!re)
{
NSLog(@正则表达式匹配错误%@,[error localizedDescription]);
}
NSArray * arr = [re matchesInString:text options:
0
range:NSMakeRange(
0
, text.length)];
if
(!arr.count)
//说明字符串中没有表情通配符,是普通的文本,则计算文本size
{
NSDictionary *dic=@{NSFontAttributeName: [UIFont systemFontOfSize:
14
]};
CGSize size1=[text boundingRectWithSize:CGSizeMake(
160
,
1000
) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
if
(size1.height<=
60
)
{
size1.height=
60
;
}
else
{
size1.height+=
15
;
}
return
size1;
}
NSBundle *bundle = [NSBundle mainBundle];
NSString * path = [bundle pathForResource:
@emotions
ofType:
@plist
];
NSArray * face = [[NSArray alloc]initWithContentsOfFile:path];
//如果有多个表情图,必须从后往前替换,因为替换后Range就不准确了
for
(
int
j =(
int
) arr.count -
1
; j >=
0
; j--) {
//NSTextCheckingResult里面包含range
NSTextCheckingResult * result = arr[j];
for
(
int
i =
0
; i < face.count; i++) {
if
([[text substringWithRange:result.range] isEqualToString:face[i][
@chs
]])
{
NSString * imageName = [NSString stringWithString:face[i][
@png
]];
NSTextAttachment * textAttachment = [[NSTextAttachment alloc]init];
textAttachment.image = [UIImage imageNamed:imageName];
NSAttributedString * imageStr = [NSAttributedString attributedStringWithAttachment:textAttachment];
[attStr replaceCharactersInRange:result.range withAttributedString:imageStr];
break
;
}
}
}
CGSize size2=[attStr boundingRectWithSize:CGSizeMake(
180
,
1000
) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
size2.height+=
40
;
//表情文字增加高度
return
size2;
//返回属性字符串的尺寸
}