需要为图像视图设置色调…我使用它的方式如下:
imageView.setColorFilter(R.color.blue,android.graphics.PorterDuff.Mode.MULTIPLY);
但这并没有改变……
需要为图像视图设置色调…我使用它的方式如下:
imageView.setColorFilter(R.color.blue,android.graphics.PorterDuff.Mode.MULTIPLY);
但这并没有改变……
当前回答
如果你正在改变对焦的色调,请试试这个
DrawableCompat.setTint(imgView.getDrawable(),
ContextCompat.getColor(context, R.color.blue));
其他回答
更新: @ADev在他的回答中有更新的解决方案,但他的解决方案需要更新的支持库- 25.4.0或以上。
你可以改变色调,很容易在代码中通过:
imageView.setColorFilter(颜色。Argb (255, 255, 255, 255));//白色色调
如果你想要色彩鲜艳的话
imageView.setColorFilter(ContextCompat.getColor(context, R.color.COLOR_YOUR_COLOR), android.graphics.PorterDuff.Mode.MULTIPLY);
对于可绘制的向量
imageView.setColorFilter(ContextCompat.getColor(context, R.color.COLOR_YOUR_COLOR), android.graphics.PorterDuff.Mode.SRC_IN);
正如@milosmns所说,你应该使用 imageView.setColorFilter (getResouces () .getColor (R.color.blue) android.graphics.PorterDuff.Mode.MULTIPLY);
这个API需要颜色值而不是颜色资源id,这就是为什么你的语句没有工作的根本原因。
Random random=new Random;
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
ColorFilter cf = new PorterDuffColorFilter(Color.rgb(random.nextInt(255), random.nextInt(255), random.nextInt(255)),Mode.OVERLAY);
imageView.setImageResource(R.drawable.ic_bg_box);
imageView.setColorFilter(cf);
@Hardik说得对。代码中的另一个错误是在引用xml定义的颜色时。你只将id传递给setColorFilter方法,而你应该使用id来定位颜色资源,并将资源传递给setColorFilter方法。重写下面的原始代码。
如果这一行在你的活动中:
imageView.setColorFilter(getResources().getColor(R.color.blue), android.graphics.PorterDuff.Mode.MULTIPLY);
否则,你需要引用你的主活动:
Activity main = ...
imageView.setColorFilter(main.getResources().getColor(R.color.blue), android.graphics.PorterDuff.Mode.MULTIPLY);
注意,其他类型的资源也是如此,比如整数、bool、维度等。除了string,你可以直接在你的Activity中使用getString(),而不需要首先调用getResources()(不要问我为什么)。
否则,您的代码看起来很好。(虽然我还没有研究setColorFilter方法太多…)
加上ADev的答案(在我看来是最正确的),因为Kotlin的广泛采用,以及它有用的扩展函数:
fun ImageView.setTint(context: Context, @ColorRes colorId: Int) {
val color = ContextCompat.getColor(context, colorId)
val colorStateList = ColorStateList.valueOf(color)
ImageViewCompat.setImageTintList(this, colorStateList)
}
我认为这是一个在任何Android项目中都有用的功能!