在大多数图形程序(如Photoshop和Gimp(中,都有一个着色功能,因此您可以使用您选择的颜色轻松为灰度图像着色。我想对我的Android应用程序中的图像做同样的事情。我一直在研究setColorFilter函数。这就是我尝试过的。
ImageView border = (ImageView) findViewById(R.id.imageView);
int color = Color.parseColor("#F57F17"); // the color to use
border.setColorFilter(color, PorterDuff.Mode.OVERLAY);
这完全符合我的需求。唯一的问题是它还为图像中的透明区域着色。我希望透明区域保持透明。
有什么办法可以做到这一点吗?
您正在寻找SRC_ATOP:
ImageView border = (ImageView) findViewById(R.id.imageView);
int color = Color.parseColor("#F57F17"); // the color to use
border.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
为
可绘制对象着色,然后将其重新设置。我使用绑定和适配器来覆盖可绘制对象的图像颜色。
例如,我根据以下所选状态更改可绘制对象颜色:
@JvmStatic
@BindingAdapter("backgroundDrawableChange")
fun backgroundDrawableChange(view: RelativeLayout, isSelected: Boolean){
var bgDrawable: LayerDrawable = view.background as LayerDrawable
var shape: GradientDrawable = bgDrawable.findDrawableByLayerId(R.id.shapeId) as GradientDrawable
shape.setColor(Color.parseColor((if (isSelected) YACustomPreference.getInstance(view.context).getPrimaryColorHex() else YACustomPreference.getInstance(view.context).getWhite())))
}
下面是在需要更多动态控制时重写菜单项颜色的另一个示例。
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_info_fragment, menu)
try{
//get drawable filter, change color, and reassign
var filterDrawable = menu.findItem(R.id.action_filter).icon
filterDrawable = DrawableCompat.wrap(filterDrawable)
DrawableCompat.setTint(filterDrawable, Color.parseColor(YACustomPreference.getInstance(activity!!).getPrimaryTextColorHex()))
menu.findItem(R.id.action_filter).icon = filterDrawable
//get searchview drawable change color and setup listener
mSearchView = menu.findItem(R.id.action_search)?.actionView as SearchView
mSearchView?.setOnQueryTextListener(this)
val searchDrawableImageView = mSearchView?.findViewById<View>(androidx.appcompat.R.id.search_button) as ImageView
val searchDrawable = ResourcesCompat.getDrawable(resources, R.drawable.ic_search_action, null)
DrawableCompat.setTint(searchDrawable!!, Color.parseColor(YACustomPreference.getInstance(activity!!).getPrimaryTextColorHex()))
searchDrawableImageView.setImageDrawable(searchDrawable)
}catch (ex: Exception){
A35Log.e(TAG, "Error updating SearchView drawable icon")
}
super.onCreateOptionsMenu(menu, inflater)
}
这应该有望帮助您在终点线上完成您正在做的事情。快乐编码。