且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

android 文字叠加显示在图片之上控件的实现 -- 充分利用TextView

更新时间:2021-09-23 01:19:07

1.通过定义XML方式实现

<TextView 
        android:id="@+id/txtMsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"         android:textSize="19px"
        android:gravity="center_horizontal"
        android:text="测试文字"
        android:drawablePadding="-20px"  //设置字体和图片之间的距离, 这是实现文字叠加显示在图片之上的关键点~
        android:drawableTop="@drawable/ic_launcher" // 设置图片显示在文字的上方
        />

2.通过动态代码实现
TextView v = new TextView(this.getApplicationContext());
 v.setCompoundDrawablePadding(-20);    
v.setGravity(Gravity.CENTER_HORIZONTAL);   
Drawable image = getResources().getDrawable(icons[i]);

image.setBounds(0, 0, image.getMinimumWidth(), image.getMinimumHeight());//非常重要,必须设置,否则图片不会显示
v.setCompoundDrawables(null,image, null, null);            
v.setText("测试文字");  
v.setTextSize(TypedValue.COMPLEX_UNIT_PX,19);//设置字体大小为19px
android 文字叠加显示在图片之上控件的实现 -- 充分利用TextView