programing

안드로이드에서 이미지 보기에 대한 틴트를 프로그래밍 방식으로 설정하는 방법은 무엇입니까?

oldcodes 2023. 6. 3. 08:42
반응형

안드로이드에서 이미지 보기에 대한 틴트를 프로그래밍 방식으로 설정하는 방법은 무엇입니까?

이미지 보기에 대한 색조를 설정해야 합니다...다음과 같은 방식으로 사용하고 있습니다.

imageView.setColorFilter(R.color.blue,android.graphics.PorterDuff.Mode.MULTIPLY);

하지만 변하지 않아요...

업데이트:
@ADEV의 답변에는 새로운 솔루션이 있지만, ADEV의 솔루션에는 25.4.0 이상의 새로운 지원 라이브러리가 필요합니다.


다음을 통해 코드에서 색조를 매우 쉽게 변경할 수 있습니다.

imageView.setColorFilter(Color.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);

은 대분의답다같다습니음과변은을 사용하는 것을 .setColorFilter원래 요청했던 것이 아닙니다.

사용자 @Tad는 올바른 방향으로 답을 가지고 있지만 API 21+에서만 작동합니다.

버전에서 하려면 모Android 버전설정려다사다용니합음을든면하색조를 합니다.ImageViewCompat:

ImageViewCompat.setImageTintList(imageView, ColorStateList.valueOf(yourTint));

:yourTint이 경우 "color int"여야 합니다.와 같은 색 이 있다면,R.color.blue색상을 먼저 로드해야 합니다.

ContextCompat.getColor(context, R.color.blue);

이것은 나에게 효과가 있었습니다.

mImageView.setColorFilter(ContextCompat.getColor(getContext(), R.color.green_500));

@하딕이 옳아요.코드의 또 다른 오류는 XML 정의 색상을 참조할 때 발생합니다.당신은 ID만 전달했습니다.setColorFilterID를 사용하여 색상 리소스를 찾고 리소스를 전달해야 하는 경우 방법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);

이는 정수, 풀, 차원 등 다른 유형의 리소스에도 해당됩니다.문자열을하고 직접 할 수 하지 않습니다.getString() 전화를 걸 필요가 없는 활동에서getResources()(이유는 묻지 마십시오.)

그렇지 않으면 코드가 좋아 보입니다.(비록 나는 조사하지 않았지만.setColorFilter메서드가 너무 많습니다...)

ADev 덕분에 단순화된 확장 기능 향상

fun ImageView.setTint(@ColorRes colorRes: Int) {
    ImageViewCompat.setImageTintList(this, ColorStateList.valueOf(ContextCompat.getColor(context, colorRes)))
}

용도:-

imageView.setTint(R.color.tintColor)

내가 모든 방법을 시도했지만 그것들은 나에게 효과가 없었습니다.

저는 다른 PortDuff를 사용하여 해결책을 얻습니다.모드.

imgEstadoBillete.setColorFilter(context.getResources().getColor(R.color.green),PorterDuff.Mode.SRC_IN);

색상이 16진수 투명도를 가진 경우 아래 코드를 사용합니다.

ImageViewCompat.setImageTintMode(imageView, PorterDuff.Mode.SRC_ATOP);
ImageViewCompat.setImageTintList(imageView, ColorStateList.valueOf(Color.parseColor("#80000000")));

색조 지우기

ImageViewCompat.setImageTintList(imageView, null);

롤리팝부터는 새 팔레트 클래스와 함께 작동하는 비트맵 드로잉에 대한 색조 방법도 있습니다.

공용 보이드 세트 틴트리스트(색상 상태 리스트 틴트)

그리고.

public void setTintMode(PorterDuff).모드 틴트 모드)

이전 버전의 Android에서는 DrawableCompat 라이브러리를 사용할 수 있습니다.

단순 및 한 줄

imageView.setColorFilter(activity.getResources().getColor(R.color.your_color));

이거 먹어봐요.지원 라이브러리가 지원하는 모든 Android 버전에서 작동해야 합니다.

public static Drawable getTintedDrawableOfColorResId(@NonNull Context context, @NonNull Bitmap inputBitmap, @ColorRes int colorResId) {
    return getTintedDrawable(context, new BitmapDrawable(context.getResources(), inputBitmap), ContextCompat.getColor(context, colorResId));
}

public static Drawable getTintedDrawable(@NonNull Context context, @NonNull Bitmap inputBitmap, @ColorInt int color) {
    return getTintedDrawable(context, new BitmapDrawable(context.getResources(), inputBitmap), color);
}

public static Drawable getTintedDrawable(@NonNull Context context, @NonNull Drawable inputDrawable, @ColorInt int color) {
    Drawable wrapDrawable = DrawableCompat.wrap(inputDrawable);
    DrawableCompat.setTint(wrapDrawable, color);
    DrawableCompat.setTintMode(wrapDrawable, PorterDuff.Mode.SRC_IN);
    return wrapDrawable;
}

위의 항목 중 하나를 사용하여 작업할 수 있습니다.

DrawableCompat의 더 흥미로운 기능은 여기 문서에서 읽을 수 있습니다.

확장 기능을 사용하여 Tinting을 설정 및 설정 해제하는 Kotlin 솔루션:

fun ImageView.setTint(@ColorInt color: Int?) {
    if (color == null) {
        ImageViewCompat.setImageTintList(this, null)
        return
    }
    ImageViewCompat.setImageTintMode(this, PorterDuff.Mode.SRC_ATOP)
    ImageViewCompat.setImageTintList(this, ColorStateList.valueOf(color))
}

Android에서 프로그래밍 방식으로 이미지 보기에 대한 색조를 설정

안드로이드에는 두 가지 방법이 있습니다.

1)

imgView.setColorFilter(context.getResources().getColor(R.color.blue));

2)

 DrawableCompat.setTint(imgView.getDrawable(),
                     ContextCompat.getColor(context, R.color.blue));

제가 누군가를 도와줬기를 바랍니다 :-)

색조에 색상 선택기를 사용할 수 있습니다.

mImageView.setEnabled(true);

activity_main.xml:

<ImageView
    android:id="@+id/image_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_arrowup"
    android:tint="@color/section_arrowup_color" />

section_contraup_colorup_color.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@android:color/white" android:state_enabled="true"/>
    <item android:color="@android:color/black" android:state_enabled="false"/>
    <item android:color="@android:color/white"/>
</selector>

코틀린이 널리 채택된 이후 ADev의 답변(내 생각에 가장 맞는 답변)과 유용한 확장 기능을 추가하면 다음과 같습니다.

fun ImageView.setTint(context: Context, @ColorRes colorId: Int) {
    val color = ContextCompat.getColor(context, colorId)
    val colorStateList = ColorStateList.valueOf(color)
    ImageViewCompat.setImageTintList(this, colorStateList)
}

이것은 안드로이드 프로젝트에서 유용하게 사용할 수 있는 기능이라고 생각합니다!

색상 설정 및 설정 해제를 위한 코틀린의 확장 기능입니다.

fun ImageView.setTint(@ColorRes color: Int?) {
  if (color == null) {
    ImageViewCompat.setImageTintList(this, null)
  } else {
    ImageViewCompat.setImageTintList(this, ColorStateList.valueOf(ContextCompat.getColor(context, color)))
}}

용도:yourImageView.setTint(R.color.white)및 설정및 거제전용전::yourImageView.setTint(null)

첫 번째 답은 나에게 효과가 없었기 때문에:

//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을 사용하여 이 문제를 해결할 수 있습니다.

제가 누군가를 도와줬기를 바랍니다 :-)

롤리팝에서 시작해서, 당신이 사용할 수 있는 방법이 있습니다...장점은 그것이 필요하다는 것입니다.ColorStateList단일 색상이 아니라 이미지의 색조를 상태 인식으로 만듭니다.

롤리팝 이전 장치에서는 드로잉 가능한 색상을 지정한 다음 로 설정하여 동일한 동작을 수행할 수 있습니다.ImageView를 그릴수 있습니다.

ColorStateList csl = AppCompatResources.getColorStateList(context, R.color.my_clr_selector);
Drawable drawable = DrawableCompat.wrap(imageView.getDrawable());
DrawableCompat.setTintList(drawable, csl);
imageView.setImageDrawable(drawable);
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);

@가 말했듯이,은 @milosmonds, 당은사야합니다용해이듯했신을 사용해야 합니다. imageView.setColorFilter(getResouces().getColor(R.color.blue),android.graphics.PorterDuff.Mode.MULTIPLY);

이 API는 color resource id 대신 color value가 필요합니다. 이것이 당신의 진술이 작동하지 않은 근본 원인입니다.

사용하지 PoterDuff.Mode,사용하다setColorFilter()모두에게 효과가 있습니다.

ImageView imageView = (ImageView) listItem.findViewById(R.id.imageView);
imageView.setColorFilter(getContext().getResources().getColor(R.color.msg_read));

선택기를 색조로 설정하려는 경우:

ImageViewCompat.setImageTintList(iv, getResources().getColorStateList(R.color.app_icon_click_color));

나는 파티에 늦었지만 위에서 나의 해결책을 보지 못했습니다.다음을 통해 틴트 색상을 설정할 수 있습니다.setImageResource()minSdkVersion은 24도입니다.

먼저선를생저합장니다에 ./drawable 폴더는 그것을 산자폴더i(더(나는 그것을)라고 .ic_color_white_green_search.xml)

<!-- Focused and not pressed -->
<item android:state_focused="true"
      android:state_pressed="false">

    <bitmap android:src="@drawable/ic_search"
            android:tint="@color/branding_green"/>
</item>

<!-- Focused and pressed -->
<item android:state_focused="true"
      android:state_pressed="true">

    <bitmap android:src="@drawable/ic_search"
            android:tint="@color/branding_green"/>
</item>

<!-- Default -->
<item android:drawable="@drawable/ic_search"/>

그런 다음 다음 코드로 설정합니다.

val icon = itemView.findViewById(R.id.icon) as ImageButton
icon.setImageResource(R.drawable.ic_color_white_green_search)

저한테는 이 코드가 통합니다.카드 및 이미지 보기와 함께 사용하지만 어떤 보기에서도 색조를 변경할 수 있습니다. 카드 북마크는 제 카드 보기입니다.

var cardDrawable: Drawable = binding.cardBookmark.background
cardDrawable = DrawableCompat.wrap(cardDrawable)
DrawableCompat.setTint(cardDrawable, resources.getColor(R.color.shuffleColor))
binding.cardBookmark.background = cardDrawable

고지 사항:이것은 이 게시물에 대한 답변이 아닙니다.그러나 이 질문에 대한 답입니다. 즉, 그리기 가능한 보기 또는 이미지 보기의 색상/톤을 재설정하는 방법입니다.죄송합니다, 답변을 수락하지 않는 질문이기 때문에 여기에 올려놓고 답변을 위해 이 게시물을 참조합니다.그래서 여기에 추가하면 해결책을 찾는 사람들이 여기에 도달할 수 있습니다.

답변의 코멘트에서 @RRGT19가 언급한 바와 같이.다음을 사용하여 색상을 재설정할 수 있습니다.setImageTintList()그리고 지나가는nulltintList로 지정합니다.그것은 저에게 마법처럼 효과가 있었습니다.

ImageViewCompat.setImageTintList(imageView, null)

만약 당신이 포커스 체인지에서 틴트를 바꾸고 있다면 이것을 시도해 보세요.

DrawableCompat.setTint(imgView.getDrawable(),
                 ContextCompat.getColor(context, R.color.blue));

내가 모든 방법을 시도했지만 그것들은 나에게 효과가 없었습니다.

선택한 색상의 정수 값을 반환하는 colorPicker 라이브러리를 통해 색상을 변경하는 경우에 대비하여 특별히 솔루션을 제공합니다.

widgetIcon내 ImageView 및selectedColorcolorPicker의 색상입니다.

var imageDrawable: Drawable = widgetIcon.background
        imageDrawable = DrawableCompat.wrap(imageDrawable)
        DrawableCompat.setTint(imageDrawable, selectedColor)
        widgetIcon.background = imageDrawable

사용 중인 Java에서

imageView.setImageTintList(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.red)));

정확한 답은 아니지만 더 간단한 대안:

  • 이미지 위에 다른 보기 배치
  • 원하는 효과를 얻기 위해(프로그래밍 방식으로) 보기의 알파 값을 변경합니다.

다음은 이에 대한 토막글입니다.

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="@dimen/height120"
        android:contentDescription="@string/my_description"
        android:scaleType="fitXY"
        android:src="@drawable/my_awesome_image"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="@dimen/height120"
        android:alpha="0.5"
        android:background="@color/my_blue_color"/>
</FrameLayout>

언급URL : https://stackoverflow.com/questions/20121938/how-to-set-tint-for-an-image-view-programmatically-in-android

반응형