美文网首页
android 图文混排图片居中实现

android 图文混排图片居中实现

作者: 三十二蝉 | 来源:发表于2018-02-22 00:16 被阅读86次

    前言

    android的图文混排是基于SpannableString中设置ImageSpan实现的,系统默认的ImageSpan只有两种排列方式:

     底部对齐
         */
        public static final int ALIGN_BOTTOM = 0;
        
        /**
         基线对齐
         */
        public static final int ALIGN_BASELINE = 1;
    

    设计有时候需要图片基于文字中心对齐,这里就需要继承ImageSpan重写draw方法。

    代码

    public class CenterAlignImageSpan extends ImageSpan {
        public CenterAlignImageSpan(Drawable d) {
            super(d);
        }
    
        @Override
        public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
            Drawable drawable = getDrawable();
            Paint.FontMetricsInt fm = paint.getFontMetricsInt();
            int transY = (y + fm.descent + y + fm.ascent) / 2 - drawable.getBounds().bottom / 2;
            canvas.save();
            canvas.translate(x, transY);
            drawable.draw(canvas);
            canvas.restore();
        }
    }
    

    测试代码如下:

    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            TextView textView = findViewById(R.id.test_tx);
            String str = "this is a test";
            SpannableString spanString = new SpannableString(str);
            Drawable drawable = this.getResources().getDrawable(R.drawable.test);
            drawable.setBounds(0, 0, 40, 40);   //设置图片显示区域大小
            CenterAlignImageSpan imageSpan = new CenterAlignImageSpan(drawable);
            spanString.setSpan(imageSpan, spanString.length() - 3, spanString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            SpannableStringBuilder builder = new SpannableStringBuilder();
            builder.append("测试: ");
            builder.append(spanString);
            textView.setText(builder);
        }
    

    相关文章

      网友评论

          本文标题:android 图文混排图片居中实现

          本文链接:https://www.haomeiwen.com/subject/mvkatftx.html