代码
public class MainActivity extends AppCompatActivity {
private TextView text;
private static Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
text = findViewById(R.id.text);
String msg = "吴彦祖的情侣";
String nick = "吴彦祖";
String vip = "vip";
String manager = "管";
String content = " 哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈";
String space = " "; //添加空格使各个图片标示有间隔
float scale = getResources().getDisplayMetrics().density;
paint.setTextSize((int) (12 * scale));
paint.setColor(getResources().getColor(R.color.white));
Rect textBound = new Rect();
paint.getTextBounds(msg, 0, msg.length(), textBound);
Log.d("MainActivity", "bound = " + textBound);
int lineHeight = text.getLineHeight();
int padding = (int)(8 * scale);
Bitmap bitmap = Bitmap.createBitmap(textBound.width() + padding * 2, lineHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
NinePatchDrawable backgroundDrawable = (NinePatchDrawable)getResources().getDrawable(R.mipmap.yidui_img_sweetheart_bg);
backgroundDrawable.setBounds(new Rect(0, 0, textBound.width() + padding * 2, lineHeight));
backgroundDrawable.draw(canvas);
canvas.drawText(msg, padding, canvas.getHeight() / 2f + (Math.abs(paint.ascent()) - paint.descent()) / 2, paint);
SpannableStringBuilder str = new SpannableStringBuilder();
str.append(msg);
int start = 0;
int end = msg.length();
ImageSpan imageSpan = new ImageSpan(this, bitmap);
str.setSpan(imageSpan, start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
str.append(space);
str.append(vip);
start = end + space.length();
end += vip.length() + space.length();
Drawable vipDrawable = getResources().getDrawable(R.mipmap.ic_new_vip);
vipDrawable.setBounds( 0 , 0 , 100 , lineHeight);
ImageSpan vipImageSpan = new ImageSpan(vipDrawable);
str.setSpan(vipImageSpan, start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
str.append(space);
str.append(manager);
start = end + space.length();
end += manager.length() + space.length();
Drawable managerDrawable = getResources().getDrawable(R.mipmap.yidui_live_manager_icon);
managerDrawable.setBounds( 0 , 0 , 70 , lineHeight);
ImageSpan managerImageSpan = new ImageSpan(managerDrawable);
str.setSpan(managerImageSpan, start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
str.append(space);
str.append(nick);
start = end + space.length();
end += + nick.length() + space.length();
ForegroundColorSpan nickColorSpan = new ForegroundColorSpan(Color.parseColor("#A4DFEB"));
str.setSpan(nickColorSpan ,start , end ,Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
str.append(content);
start = end;
end += content.length();
ForegroundColorSpan contentColorSpan = new ForegroundColorSpan(Color.parseColor("#BBBFEB"));
str.setSpan(contentColorSpan , start , end ,Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
text.setText(str);
}
}
样式