如果 UI 对同一种图片 选中 非选中状态 只是颜色的变化 ,有的还有夜间模式,想一想一个app中药多少对应的套图,apk的包越来越大,老板不满意了,这时想杀产品狗和UI设计的心都有,不过天无绝人之路:请继续阅读:
核心 为.png 着色,前提是 白色和透明图片。
package com.xuan.drawabletinted; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LightingColorFilter; import android.graphics.Paint; import android.graphics.drawable.BitmapDrawable; public final class TintedBitmapDrawable extends BitmapDrawable { private int tint; private int alpha; public TintedBitmapDrawable(final Resources res, final Bitmap bitmap, final int tint) { super(res, bitmap); this.tint = tint; this.alpha = Color.alpha(tint); } public TintedBitmapDrawable(final Resources res, final int resId, final int tint) { super(res, BitmapFactory.decodeResource(res, resId)); this.tint = tint; this.alpha = Color.alpha(tint); } public void setTint(final int tint) { this.tint = tint; this.alpha = Color.alpha(tint); } @Override public void draw(final Canvas canvas) { final Paint paint = getPaint(); if (paint.getColorFilter() == null) { paint.setColorFilter(new LightingColorFilter(tint, 0)); paint.setAlpha(alpha); } super.draw(canvas); } }
package com.xuan.drawabletinted; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.widget.ImageView; public class MainActivity extends Activity { ImageView imageView, imageView2, imageView3, imageView4, imageView5; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = (ImageView) findViewById(R.id.img_view); imageView.setImageDrawable(new TintedBitmapDrawable(getResources(), R.mipmap.ic_add_course, Color.BLUE)); imageView2 = (ImageView) findViewById(R.id.img_view2); imageView2.setImageDrawable(new TintedBitmapDrawable(getResources(), R.mipmap.ic_add_course, Color.YELLOW)); imageView3 = (ImageView) findViewById(R.id.img_view3); imageView3.setImageDrawable(new TintedBitmapDrawable(getResources(), R.mipmap.ic_add_course, Color.BLACK)); imageView4 = (ImageView) findViewById(R.id.img_view4); imageView4.setImageDrawable(new TintedBitmapDrawable(getResources(), R.mipmap.ic_add_course, Color.GREEN)); imageView5 = (ImageView) findViewById(R.id.img_view5); imageView5.setImageDrawable(new TintedBitmapDrawable(getResources(), R.mipmap.ic_add_course, Color.MAGENTA)); } }
说到这里,有的人可能不乐意了:Lollipop不是支持着色了么?回答:这是兼容Lollipop一下的版本
可能又要问,图片的圆形 阴影 标签什么的...没关系,这么简单的代码,相信你能改出来