[关闭]
@RitcheeQinG 2020-09-07T02:12:06.000000Z 字数 1634 阅读 223

自定义带背景的Spannable

Android


内容较老,仅提供思路

  1. import android.content.res.Resources;
  2. import android.graphics.Canvas;
  3. import android.graphics.Color;
  4. import android.graphics.Paint;
  5. import android.graphics.Rect;
  6. import android.graphics.Typeface;
  7. import android.graphics.drawable.Drawable;
  8. import android.support.annotation.NonNull;
  9. import android.support.v4.content.res.ResourcesCompat;
  10. import android.text.style.ImageSpan;
  11. import com.imlib.common.utils.IMUtils;
  12. import net.appcloudbox.uniform.HSApplication;
  13. public class CenterAlignSpanWithNum extends ImageSpan {
  14. private int resId;
  15. public CenterAlignSpanWithNum(@NonNull Drawable d, int resId) {
  16. super(d);
  17. this.resId = resId;
  18. }
  19. @Override
  20. public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, @NonNull Paint paint) {
  21. Drawable background = getDrawable();
  22. Rect bounds = background.getBounds();
  23. Paint.FontMetricsInt fm = paint.getFontMetricsInt();
  24. int transY = (y + fm.descent + y + fm.ascent) / 2 - bounds.bottom / 2;//计算y方向的位移
  25. canvas.save();
  26. canvas.translate(x, transY);//绘制图片位移一段距离
  27. background.draw(canvas);
  28. canvas.restore();
  29. String str = text.subSequence(start, end).toString();
  30. paint.setTextSize(IMUtils.dip2px(13));
  31. Rect textBounds = new Rect();
  32. //获得字符串所占空间大小
  33. paint.getTextBounds(str, 0, str.length(), textBounds);
  34. paint.setColor(Color.parseColor("#121212"));
  35. Typeface tf = null;
  36. try {
  37. tf = ResourcesCompat.getFont(HSApplication.getContext(), resId);
  38. } catch (Resources.NotFoundException e) {
  39. e.printStackTrace();
  40. }
  41. if (null == tf) {
  42. tf = Typeface.create("sans-serif_medium", Typeface.NORMAL);
  43. paint.setFakeBoldText(true); // semi-bold要比bold细一点
  44. }
  45. paint.setTypeface(tf);
  46. float textX = x + bounds.width() / 2f - textBounds.width() / 2f + IMUtils.dip2px(2);
  47. canvas.drawText(str, textX, (float) y, paint);
  48. }
  49. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注