天天看点

【完美解决系列】解决在Android中使用background时导致图片被拉伸的问题

在项目中使用到了修改TextView的background图片,但是发现直接给background设置图标,运行app在手机上此background图片会被拉伸,查了一下google 文档,发现还有另外一种设置background的方法,而且可以解决图片被拉伸的问题。(此方法适用于任何的View使用,很赞!)

直接使用以XML Bitmap的形式定义background就可以了。

1、创建一个xml文件,如:bitmap_hot_1.xml。在代码中src设置成你需要的图片。

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:gravity="top"
    android:src="@drawable/ic_hot_1"
    android:tileMode="disabled"></bitmap>
           

2、把bitmap_hot_1放入到drawable文件夹中

3、使用时直接调用bitmap_hot_1。(拿TextView举例)

TextView tv_1;
tv_1.setBackgroundResource(R.drawable.bitmap_hot_1);
           

或者在TextView的xml中定义

<TextView
    android:id="@+id/tv_1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"   
    android:text="1"
    android:background="@drawable/bitmap_hot_1"/>