Drawable的Tint变色(让Android也能有iOS那么方便的图片色调转换)

Drawable的Tint变色(让Android也能有iOS那么方便的图片色调转换)

字数590 阅读475 评论0 喜欢1java

开发iOS应用的时候,图片不少时候只要一张,改变不一样的色调就能变化出“正常、点击、选中、不能编辑”等不一样的效果。而Android之前是经过多张图片(不少时候是一张基础图而后美工修改出几种不一样颜色对应不一样效果,对比iOSTint效果简直是low爆了有木有),之前在想,若是Android也能有这么方便的效果就行了。嗯嗯,今天就来介绍下AndroidDrawable方法。android

其实关键的类就是 Android Support v4 的包中提供了 DrawableCompat 。app

咱们能够封装一个静态函数方便使用,以下:函数

public static Drawable tintDrawable(Drawable drawable, ColorStateList colors) {    final Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
    DrawableCompat.setTintList(wrappedDrawable, colors);    return wrappedDrawable;
}

新建一个Activity,并在layout加入ImageButton做为演示效果的控件。spa

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageButton
        android:id="@+id/ivButton"
        android:src="@drawable/batman"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" /></RelativeLayout>

好了,网上找一个图片取名batman,就是上面ImageButton的src
code


原图xml

接下来咱们在Activity代码中把src由黑色改成白色。图片

ImageButton ivButton = (ImageButton) findViewById(R.id.ivButton);
Drawable src = ivButton.getDrawable();
ivButton.setImageDrawable(tintDrawable(src,ColorStateList.valueOf(Color.WHITE)));

运行一下,ImageButton的图片batman就神奇的变成白色了~utf-8


白色开发

那么咱们平时是经过selector来设置不一样状态图片的,咱们须要点击来改变图片颜色怎么办呢?
不用担忧,一样支持selector来改变颜色。接下来咱们要建立这个控制状态颜色的selector
color目录下new 一个 xml取名为“selector_imagebutton_batman.xml”做为咱们的控制颜色selector,点击变为粉红色,正常状态为蓝色。

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="#FF4081" android:state_pressed="true" />
    <item android:color="#3F51B5" /></selector>

而后咱们把刚刚传给tintDrawable函数的参数改成selector便可

ivButton = (ImageButton) findViewById(R.id.ivButton);
Drawable src = ivButton.getDrawable();//        ivButton.setImageDrawable(tintDrawable(src,ColorStateList.valueOf(Color.WHITE)));ivButton.setImageDrawable(tintDrawable(src,getResources().getColorStateList(R.color.selector_imagebutton_batman)));

咱们来看看效果吧~~


效果图

相关文章
相关标签/搜索