作者:大飞5678 | 来源:互联网 | 2023-05-18 22:45
SpanStringUtils工具类用途:将文本中的emoji字符处理为表情图片(利用正则,取出特定的字符并且找到相应的图片,再将图片导入ImageSpan,最终使用spannableS
SpanStringUtils 工具类
用途:将文本中的emoji字符处理为表情图片
(利用正则,取出特定的字符并且找到相应的图片,再将图片导入ImageSpan ,最终使用spannableString将ImageSpan存入)
public class SpanStringUtils {
public static SpannableString getEmotionContent(int emotion_map_type,final Context context, final TextView tv, String source) {
SpannableString spannableString = new SpannableString(source);
Resources res = context.getResources();
String regexEmotion = "\\[([\u4e00-\u9fa5\\w])+\\]";
Pattern patternEmotion = Pattern.compile(regexEmotion);
Matcher matcherEmotion = patternEmotion.matcher(spannableString);
while (matcherEmotion.find()) {
String key = matcherEmotion.group();
int start = matcherEmotion.start();
Integer imgRes = EmotionUtils.getImgByName(emotion_map_type,key);
if (imgRes != null) {
int size = (int) tv.getTextSize()*13/10;
Bitmap bitmap = BitmapFactory.decodeResource(res, imgRes);
Bitmap scaleBitmap = Bitmap.createScaledBitmap(bitmap, size, size, true);
ImageSpan span = new ImageSpan(context, scaleBitmap);
spannableString.setSpan(span, start, start + key.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
return spannableString;
}
}