web-dev-qa-db-ja.com

ShapedDrawableを使用してColorFilterをImageViewに適用する

ImageViewに設定されたAndroid:srcを持つShapedDrawable、つまり白い円があります。私が欲しいのは、いくつかのイベントに対応するランタイムでこのImageViewを色付けすることです。 imgView.setColorFilterは解決策のようですが、これを使用した後(さまざまなパラメーターを試しました)、画像が見えなくなります(画面に表示されません)。

これを解決するには?また、カラーサークルを作成するより良い方法はありますか?

39
aplavin

さて、私はこれで簡単に遊びましたが、あなたのサークルが消える問題に気付きました。 what正確にあなたが試みたことを説明せずに、Drawable自体にカラーフィルターを設定しようとしていないと思いますか? (ImageViewとは対照的に、これはBitmapDrawablesでのみ動作するようです)。

次のステートメントは、初期色として白を使用したxmlで宣言されたShapeDrawableに対して完璧に機能します。

ImageView redCircle = (ImageView) findViewById(R.id.circle_red_imageview);
ImageView greenCircle = (ImageView) findViewById(R.id.circle_green_imageview);
ImageView blueCircle = (ImageView) findViewById(R.id.circle_blue_imageview);

// we can create the color values in different ways:
redCircle.getDrawable().setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY );
greenCircle.getDrawable().setColorFilter(0xff00ff00, PorterDuff.Mode.MULTIPLY );
blueCircle.getDrawable().setColorFilter(getResources().getColor(R.color.blue), PorterDuff.Mode.MULTIPLY );

完全性のためのShapeDrawable:(ImageViewのサイズを設定します。以下を参照)

<shape xmlns:Android="http://schemas.Android.com/apk/res/Android" Android:shape="oval" >
    <solid Android:color="@Android:color/white" />
</shape>

そして、例としてImageViewsの1つ:

<ImageView
    Android:id="@+id/circle_red_imageview"
    Android:layout_width="40dp"
    Android:layout_height="40dp"
    Android:padding="5dp"
    Android:src="@drawable/circle_white" />

視覚的結果:

Screenshot of colored circles

102
MH.

画像の色を変更する場合

PorterDuff.Mode.SRC_ATOP instead
PorterDuff.Mode.MULTIPLY

上記の例で。

15

XmlのImageViewで属性Android:tintを使用できます。

例:

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

テスト済みAndroid 4.1.2および6.0.1

6

このライブラリを使用すると、非常に簡単に実行できます。 https://github.com/jrvansuita/IconHandler

次のように機能します。

Icon.on(yourImageView).color(R.color.your_color).icon(R.mipmap.your_icon).put();
0
Vansuita Jr.