Textview中显示文字图片混合效果

2017-08-10  本文已影响0人  念念不忘_2016
在开发一个IM软件时候用到了表情加文字的混合效果,下面是我实现的代码,亲测可用;
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);
}
}
上一篇下一篇

猜你喜欢

热点阅读