天天看点

关于android:tint属性的使用

 前言:

最近在网上看到一些大牛的博客里面有提到android:tint这个属性,说实话做Android开发这么多年,自己比较菜,从来没有去深入了解过android:tint这个属性,当然也就没有使用过了,但是看了大牛的讲解之后感觉这个属性很实用,能够在平时的项目中用到。能给公司的设计节省一些设计工作,并且也能提高图片资源在代码中的复用性,从而减少apk的大小。

进入正题:

如何使用android:tint这个属性呢?下面咱们就通过代码来一起看看这个android:tint这个属性都有哪些作用,能给我们的开发工作带来什么便利。

首先创建一个Activity

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView iv_image=findViewById(R.id.iv_image);
    }
}
           

其次,书写Activity对应的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/iv_image"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:src="@mipmap/icon_course_show"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
           

在布局文件中有一个ImageView控件,并且给这个控件添加了一个src属性,这个属性指向了一个icon_course_show.png的图片:

关于android:tint属性的使用
关于android:tint属性的使用

我们看到这张图片的原图是黑色的线条,再给这个ImageView加一个android:tint属性:

关于android:tint属性的使用

在右侧的preview栏中我们可以看到,图片显示出了android:tint属性所设置的颜色。项目运行一下:

关于android:tint属性的使用

这个是在布局文件里面对android:tint属性进行了使用,那么是否可以在代码中使用这个属性了呢?

关于android:tint属性的使用

我们在代码里,调用ImageView的setImageTintList方法也可以对原图进行颜色的改变。只不过目前这个方法只支持到Android5.0以后,对于Android5.0以前的兼容,大家可以参考大神的这篇文章:https://www.jianshu.com/p/6c288ff88ecf

运行之后,我们发现图片的颜色发生了变化:

关于android:tint属性的使用

好了,android:tint这个属性大家已经有所了解了。

同理,ImageVIew还有一个属性:android:backgroundTint,是针对设置了背景图的控件,不引入指定颜色的图片,而是直接在原图上通过设置backgroundTint属性来达到想要的效果。也可在代码中通过调用setBackgroundTintList来使用该属性。这里就不做过多的讲解了,很简单,大家可以动手去写代码试试。

总结:

这两个属性不但使用简单,而且解决了平时我们开发过程中,遇到的对于同一张图片,需要使用不同颜色的情况。通过使用这两个属性,可以增加图片资源的复用性,从而减少apk的大小。