需要为图像视图设置色调…我使用它的方式如下:
imageView.setColorFilter(R.color.blue,android.graphics.PorterDuff.Mode.MULTIPLY);
但这并没有改变……
需要为图像视图设置色调…我使用它的方式如下:
imageView.setColorFilter(R.color.blue,android.graphics.PorterDuff.Mode.MULTIPLY);
但这并没有改变……
当前回答
更新: @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);
其他回答
@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方法太多…)
因为第一个答案对我不起作用:
//get ImageView
ImageView myImageView = (ImageView) findViewById(R.id.iv);
//colorid is the id of a color defined in values/colors.xml
myImageView.setImageTintList(ColorStateList.valueOf(ContextCompat.getColor(getApplicationContext(), R.color.colorid)));
这似乎只适用于API 21+,但对我来说这不是问题。不过,您可以使用ImageViewCompat来解决这个问题。
我希望我能帮到大家:-)
在android中以编程方式设置图像视图的色调
我有两个方法为android:
1)
imgView.setColorFilter(context.getResources().getColor(R.color.blue));
2)
DrawableCompat.setTint(imgView.getDrawable(),
ContextCompat.getColor(context, R.color.blue));
我希望我能帮到大家:-)
正如@milosmns所说,你应该使用 imageView.setColorFilter (getResouces () .getColor (R.color.blue) android.graphics.PorterDuff.Mode.MULTIPLY);
这个API需要颜色值而不是颜色资源id,这就是为什么你的语句没有工作的根本原因。
不要使用波特达夫。模式, 使用setColorFilter()它适用于所有情况。
ImageView imageView = (ImageView) listItem.findViewById(R.id.imageView);
imageView.setColorFilter(getContext().getResources().getColor(R.color.msg_read));