没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
Android自定义自定义TextView实现文字图片居中显示的方法实现文字图片居中显示的方法
下面小编就为大家分享一篇Android自定义TextView实现文字图片居中显示的方法,具有很好的参考价值,希望
对大家有所帮助。一起跟随小编过来看看吧
最近有个需求是这样的,人民币的符号“¥”因为安卓手机系统的不一致导致符号不是完全一样,所以用美工的给的图片代替,
考虑到用的地方比较多,所以想着写一个继承于线性布局的组合控件,后来一想,安卓中不是有TextView吗,这个自带图片
的控件,后来写了个demo,因为我是用的MatchParent,导致问题出现,人民币符号不是和文字一样的居中,因此才有了这
篇博文,让我们来自定义TextView吧,这个场景用的比较多。
分析下分析下TextView的源码的源码
我们先来分析下TextView的源码,因为TextView有上下左右四个方向的图片,上下咱就先不考虑了,因为一般来说图片垂直
居中是没有问题的,我们就只处理这个left,和right方向上的图片, 我们直接看TextView的ondraw方法,因为TextView 也是
继承自View,所有的绘制都将会在这里操作
<span style="font-size:18px;">int vspace = bottom - top - compoundPaddingBottom - compoundPaddingTop;
int hspace = right - left - compoundPaddingRight - compoundPaddingLeft;
// IMPORTANT: The coordinates computed are also used in invalidateDrawable()
// Make sure to update invalidateDrawable() when changing this code.
if (dr.mShowing[Drawables.LEFT] != null) {
canvas.save();
canvas.translate(scrollX + mPaddingLeft + leftOffset,
scrollY + compoundPaddingTop +
(vspace - dr.mDrawableHeightLeft) / 2);
dr.mShowing[Drawables.LEFT].draw(canvas);
canvas.restore();
}
// IMPORTANT: The coordinates computed are also used in invalidateDrawable()
// Make sure to update invalidateDrawable() when changing this code.
if (dr.mShowing[Drawables.RIGHT] != null) {
canvas.save();
canvas.translate(scrollX + right - left - mPaddingRight
- dr.mDrawableSizeRight - rightOffset,
scrollY + compoundPaddingTop + (vspace - dr.mDrawableHeightRight) / 2);
dr.mShowing[Drawables.RIGHT].draw(canvas);
canvas.restore();
}</span>
从上面可以看到有个canvas.translate方法,大概意思是,save后,将画布向X轴和Y轴分别平移了scrollX ..和scrollY,平移
后,将left方向的图片绘制上去,最后restore还原到上个画布中,Right同理。
那这样,咱基本上就明白原理,TextView的四个方向都是通过Canvas的translate来绘制到文字的上下左右了,那咱们就只改
这个scrollX 和 scrollY就可以实现咱的需求了吧。
具体实现具体实现
1.下面写有注释,不是特别麻烦,适配drawableLeft 和 drawableRight图片,PS,xml中不要设置Gravity,这样就可以居中了,
代码如下:
<span style="font-size:18px;">package com.chaoxing.email.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.TextView;
/**
* use in xml
* use in code
*/
public class EmailCenterTextView extends TextView {
public EmailCenterTextView(Context context) {
super(context);
}
public EmailCenterTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EmailCenterTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable[] drawables = getCompoundDrawables();
if (null != drawables) {
Drawable drawableLeft = drawables[0];
资源评论
weixin_38606294
- 粉丝: 3
- 资源: 926
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功