i want to add a color filter to the imageview

廉价感情. 提交于 2019-11-29 01:58:25

问题


I'd like to add a ColorFilter to ImageView.

Currently I'm using:

ImageView iv = (ImageView)findViewById(resIdOfImageToFilter);
iv.setColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP);

I've checked Multiple Modes in PotterDuff such as SRC_IN, SRC etc., but I'm not getting any difference in any of the modes... All mode turns the whole ImageView in perfect Red color.

I need to blend RED color in the existing image so that image will look with a REDDISH tinge....


回答1:


The right way to do it was using PorterDuff.Mode.LIGHTEN.

So the updated code will be like:

ImageView iv = (ImageView)findViewById(resIdOfImageToFilter);
iv.setColorFilter(Color.RED, PorterDuff.Mode.LIGHTEN);



回答2:


You can use android:tint (link) in you xml file. Example:

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/your_drawable"
    android:tint="@color/your_color" />



回答3:


This worked for me:

in res/colors.xml:

<color name="highlight_color_filter">#A5FF0000</color>

in your Activity initialize the filter and highlight paint:

int highlightColor = context.getResources().getColor(R.color.highlight_color_filter);
PorterDuffColorFilter colorFilter = new PorterDuffColorFilter(highlightColor, PorterDuff.Mode.SRC_ATOP);

Paint redHighLight = new Paint();
redHighLight.setColorFilter(targetHitFilter);
redHighLight.setAlpha(190);

then apply the filter to the ImageView:

ImageView iv=(ImageView)findViewById(ResIdOfImageToFilter);
iv.setColorFilter(redHighLight);

if that doesn't work try applying to the ImageView drawable:

iv.getDrawable().setColorFilter(redHighLight);

hope that helps.




回答4:


Other solution, you could have kept PorterDuff.Mode.SRC_ATOP mode and use another alpha to have a transparent color.

I use 155 as Alpha value:

  final int semiTransparentGrey = Color.argb(155, 185, 185, 185);
  drawable.setColorFilter(semiTransparentGrey, PorterDuff.Mode.SRC_ATOP);



回答5:


In your xml file you can user tint For example

        <ImageView
            android:id="@+id/scrachImage_1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:tint="@color/colorAccent"
            android:src="@drawable/eagle" />

If You want programmatically add color filter then use

scratchImage_2.setColorFilter(Color.BLACK);

You Can also remove this color filter using this code:

scratchImage_2.setColorFilter(null);



来源:https://stackoverflow.com/questions/8193447/i-want-to-add-a-color-filter-to-the-imageview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!