Android TextView图文混排,图片和文字居中对齐
来源:互联网 发布:时标网络图 软件 编辑:程序博客网 时间:2024/06/05 20:56
TextView用来显示文本是最普通的用法了,有些情况需要我们再文本中显示图片,比如显示表情,下边来说说处理方法.
1.下图是项目中一个UI需求
如图需要在文本的前边显示新上标签,开始的处理方法是用了两个空间分别显示标签和文本,但是有个问题是第二行的文本不能顶头对齐,很不美观.
我们可以通过图文混排来解决上述问题,通过SpannableString来实现,在相应位置使用ImageSpan替换即可,但是imageSpan只提供了两种对齐方式,如下所示:
/**
底部对齐
*/
public static final int ALIGN_BOTTOM = 0;
/**
基线对齐
*/
public static final int ALIGN_BASELINE = 1;
但是通常UI设计肯定是图片和文字居中对齐
这里需要扩展继承ImageSpan,重写它的onDraw()方法
public class CenterAlignImageSpan extends ImageSpan { public CenterAlignImageSpan(Drawable drawable) { super(drawable); } public CenterAlignImageSpan(Bitmap b) { super(b); } @Override public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, @NonNull Paint paint) { Drawable b = getDrawable(); Paint.FontMetricsInt fm = paint.getFontMetricsInt(); int transY = (y + fm.descent + y + fm.ascent) / 2 - b.getBounds().bottom / 2;//计算y方向的位移 canvas.save(); canvas.translate(x, transY);//绘制图片位移一段距离 b.draw(canvas); canvas.restore(); }}
这是自定义ImageSpan的代码,非常少。主要的原理是把图片绘制在字体的descent线和ascent的中点位置。
在Activity中使用方法如下
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tv = (TextView) findViewById(R.id.test); SpannableString sp = new SpannableString("图文混排测排测试图文混排测试图文混排测试图文混排测试图"); //获取一张图片 Drawable drawable = getDrawable(R.drawable.star); drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //居中对齐imageSpan CenterAlignImageSpan imageSpan = new CenterAlignImageSpan(drawable); sp.setSpan(imageSpan, 0, 1, ImageSpan.ALIGN_BASELINE); //普通imageSpan 做对比 ImageSpan imageSpan2 = new ImageSpan(drawable); sp.setSpan(imageSpan2, 3, 4, ImageSpan.ALIGN_BASELINE); tv.setText(sp); }}
阅读全文
0 0
- Android TextView图文混排,图片和文字居中对齐
- Android 解决图文混排,图片和文字居中对齐问题(ImageSpan)
- TextView 图文混排,图文居中对齐
- TextView图文居中混排
- 安卓控件使用系列2:TextView实现图文(图片和文字)混排
- Android EditText和TextView图文混排
- android TextView图文混排
- android TextView图文混排
- Android图文混排功能(文字后面追加图片)
- TextView的图文混排,不同文字颜色混排
- 按钮图片和文字上下居中对齐
- android 文字图片混排,在一个TextView中显示文字穿插图片,文字变色效果
- TextView添加图片实现图文混排
- Android ImageSpan使TextView的图文居中对齐
- Android 文字和图片混排,文字环绕图片
- 图文混排,文字环绕图片效果
- android中TextView图文混排
- android textview里面显示图文混排
- MySQL主从数据复制问题解决办法
- nginx支持ssl和panthinfo和去掉index.php
- centos 6.8 x86_64下autoconf版本升级到2.69
- linux awk 命令笔记
- justfy-content用法
- Android TextView图文混排,图片和文字居中对齐
- 小学生自学奥数必备的这些书籍
- JS 和OC的数据传递
- GANs实现(Generative Adversarial Networks)
- hdu 2177 取(2堆)石子游戏
- c++版本的prim算法最小生成树
- ios app url scheme跳转到淘宝商品详情页 唤醒app
- JDeveloper环境配置WebLogic常见的问题
- tcpdump