在開發(fā)一個(gè)IM軟件時(shí)候用到了表情加文字的混合效果,下面是我實(shí)現(xiàn)的代碼,親測(cè)可用;
public class FaceView extends TextView {
BaseActivity context;
public FaceView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context=(BaseActivity) context;
}
public FaceView(Context context) {
super(context);
this.context=(BaseActivity) context;
}
/**
* 普通
* @param text
*/
public void setFaceView(CharSequence text) {
Bitmap bitmap;
Pattern pattern = Pattern.compile("\\[emo]\\w+\\[/emo]");
// 獲取匹配器
Matcher matcher = pattern.matcher(text);
SpannableStringBuilder builder = new SpannableStringBuilder(text);
while (matcher.find()) {
InputStream inputStream = null;
int start = matcher.start();
int end = matcher.end();
String facename = matcher.group();
try {
inputStream = FaceTool.getFaceInputStreamByFaceName(facename,
context.getResources());
if(inputStream==null){
continue;
}
} catch (IOException e) {
e.printStackTrace();
}
byte[] buffer = StreamTool.readStream(inputStream);
bitmap =BitmapUtil.ResizeBQ(BitmapFactory.decodeByteArray
(buffer, 0, buffer.length), context.mScreenWidth,
context.mScreenHeight) ;
ImageSpan span = new ImageSpan(getContext(), bitmap,
DynamicDrawableSpan.ALIGN_BOTTOM);
builder.setSpan(span, start, end,
SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);
}
setText(builder);
}
/**
* 聊天歷史
* @param text
* @param msgDB
*/
public void setFaceView(CharSequence text,MessageSQLUtil msgDB) {
Bitmap bitmap;
Pattern pattern = Pattern.compile("\\[img\\].+\\[\\/img\\]|\\[emo]\\w+\\[/emo]");
Matcher matcher = pattern.matcher(text);
SpannableStringBuilder builder = new SpannableStringBuilder(text);
while (matcher.find()) {
InputStream inputStream = null;
int start = matcher.start();
int end = matcher.end();
String facename = matcher.group();
try {
inputStream = FaceTool.getFaceInputStreamByFaceName(
context,facename,
getResources(),msgDB);
} catch (IOException e) {
e.printStackTrace();
}
byte[] buffer = StreamTool.readStream(inputStream);
try {
bitmap =BitmapUtil.ResizeBQ(BitmapFactory.decodeByteArray
(buffer, 0, buffer.length), context.mScreenWidth,
context.mScreenHeight) ;
ImageSpan span = new ImageSpan(getContext(), bitmap,
DynamicDrawableSpan.ALIGN_BOTTOM);
builder.setSpan(span, start, end,
SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);
} catch (Exception e) {
continue;
}
}
setText(builder);
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。