programing

안드로이드에서 드로블의 색상을 변경하는 방법은?

bestprogram 2023. 9. 19. 21:20

안드로이드에서 드로블의 색상을 변경하는 방법은?

저는 안드로이드 어플리케이션을 작업하고 있으며, 소스 이미지에서 로딩 중인 드로잉이 있습니다.이 이미지에서는 흰색 픽셀을 모두 다른 색으로 변환하여 파란색이라고 말한 후 나중에 사용할 수 있도록 결과 Drawable 객체를 캐시하고 싶습니다.

예를 들어, 가운데에 하얀 원이 있는 20x20 PNG 파일을 가지고 있고, 원 밖의 모든 것이 투명하다고 가정해 보겠습니다.흰색 원을 파란색으로 바꾸고 결과를 캐시하는 가장 좋은 방법은 무엇입니까?해당 원본 이미지를 사용하여 여러 개의 새로운 Drawables(예: 파란색, 빨간색, 녹색, 주황색 등)를 생성하려면 답이 바뀝니다.

컬러매트릭스를 어떤 식으로든 사용하고 싶다는 생각이 들지만, 어떻게 사용할지 잘 모르겠습니다.

엔 그냥 될 것 같아요.Drawable.setColorFilter( 0xffff0000, Mode.MULTIPLY )이렇게 것 같습니다 이렇게 하면 흰색 픽셀이 빨간색으로 설정되지만 투명 픽셀에 영향을 주지는 않을 것 같습니다.

그림 그리기 #setColorFilter 참조

이 코드를 사용해 보십시오.

ImageView lineColorCode = (ImageView)convertView.findViewById(R.id.line_color_code);
int color = Color.parseColor("#AE6118"); //The color u want             
lineColorCode.setColorFilter(color);

롤리팝 이전에 질문했던 질문이지만 안드로이드 5.+에서 이것을 할 수 있는 좋은 방법을 추가하고 싶습니다.원본을 참조하는 xml 그리기 가능을 만들고 다음과 같이 틴트를 설정합니다.

<?xml version="1.0" encoding="utf-8"?>
<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/ic_back"
    android:tint="@color/red_tint"/>

새로운 지원 v4는 틴트를 api 4로 되돌립니다.

이렇게 하면 됩니다.

public static Drawable setTint(Drawable d, int color) {
    Drawable wrappedDrawable = DrawableCompat.wrap(d);
    DrawableCompat.setTint(wrappedDrawable, color);
    return wrappedDrawable;
}

ColorMatrixColorFilter 투명성은 유지됩니다.

int iColor = Color.parseColor(color);

int red   = (iColor & 0xFF0000) / 0xFFFF;
int green = (iColor & 0xFF00) / 0xFF;
int blue  = iColor & 0xFF;

float[] matrix = { 0, 0, 0, 0, red,
                   0, 0, 0, 0, green,
                   0, 0, 0, 0, blue,
                   0, 0, 0, 1, 0 };

ColorFilter colorFilter = new ColorMatrixColorFilter(matrix);
drawable.setColorFilter(colorFilter);

저도 사용합니다.ImageView아이콘의 경우(에서)ListView(또는 설정 화면).하지만 나는 그것을 하는 훨씬 더 간단한 방법이 있다고 생각합니다.

사용하다tint선택한 아이콘의 색상 오버레이를 변경합니다.

xml에서,

android:tint="@color/accent"
android:src="@drawable/ic_event" 

합니다에서 에 잘 합니다.AppCompat

모든 API에 대해 이 작업을 수행해야 합니다.

Drawable myIcon = getResources().getDrawable( R.drawable.button ); 
ColorFilter filter = new LightingColorFilter( Color.BLACK, Color.BLACK);
myIcon.setColorFilter(filter);

활동에서 가져온 다음 코드를 사용하여 이 작업을 수행할 수 있었습니다(레이아웃은 매우 단순하고 ImageView만 포함되어 있으며 여기에 게시되어 있지 않습니다).

private static final int[] FROM_COLOR = new int[]{49, 179, 110};
private static final int THRESHOLD = 3;

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test_colors);

    ImageView iv = (ImageView) findViewById(R.id.img);
    Drawable d = getResources().getDrawable(RES);
    iv.setImageDrawable(adjust(d));
}

private Drawable adjust(Drawable d)
{
    int to = Color.RED;

    //Need to copy to ensure that the bitmap is mutable.
    Bitmap src = ((BitmapDrawable) d).getBitmap();
    Bitmap bitmap = src.copy(Bitmap.Config.ARGB_8888, true);
    for(int x = 0;x < bitmap.getWidth();x++)
        for(int y = 0;y < bitmap.getHeight();y++)
            if(match(bitmap.getPixel(x, y))) 
                bitmap.setPixel(x, y, to);

    return new BitmapDrawable(bitmap);
}

private boolean match(int pixel)
{
    //There may be a better way to match, but I wanted to do a comparison ignoring
    //transparency, so I couldn't just do a direct integer compare.
    return Math.abs(Color.red(pixel) - FROM_COLOR[0]) < THRESHOLD &&
        Math.abs(Color.green(pixel) - FROM_COLOR[1]) < THRESHOLD &&
        Math.abs(Color.blue(pixel) - FROM_COLOR[2]) < THRESHOLD;
}

안드로이드 지원 호환 라이브러리를 사용하여 해결할 수 있습니다.:)

 // mutate to not share its state with any other drawable
 Drawable drawableWrap = DrawableCompat.wrap(drawable).mutate();
 DrawableCompat.setTint(drawableWrap, ContextCompat.getColor(getContext(), R.color.your_color))

활동에서 PNG 이미지 리소스를 단일 색상으로 색칠할 수 있습니다.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    myColorTint();
    setContentView(R.layout.activity_main);
}

private void myColorTint() {
    int tint = Color.parseColor("#0000FF"); // R.color.blue;
    PorterDuff.Mode mode = PorterDuff.Mode.SRC_ATOP;
    // add your drawable resources you wish to tint to the drawables array...
    int drawables[] = { R.drawable.ic_action_edit, R.drawable.ic_action_refresh };
    for (int id : drawables) {
        Drawable icon = getResources().getDrawable(id);
        icon.setColorFilter(tint,mode);
    }
}

이제 R.drawable을 사용할 때.* 원하는 색조로 색칠해야 합니다.추가 색상이 필요한 경우 드로잉 가능한 색상을 .mutation()할 수 있습니다.

ImageView(이미지 보기)로 그리기 가능한 설정이 있는 경우 1 라이너로 그릴 수 있습니다.

yourImageView.setColorFilter(context.getResources().getColor(R.color.YOUR_COLOR_HERE);
view.getDrawable().mutate().setColorFilter(0xff777777, PorterDuff.Mode.MULTIPLY); 

@sabadow덕분에

이 코드 스니펫은 나에게 효과가 있었습니다.

PorterDuffColorFilter porterDuffColorFilter = new PorterDuffColorFilter(getResources().getColor(R.color.your_color),PorterDuff.Mode.MULTIPLY);

imgView.getDrawable().setColorFilter(porterDuffColorFilter);
imgView.setBackgroundColor(Color.TRANSPARENT)

너무 늦었지만 누군가가 필요할 경우:

   fun setDrawableColor(drawable: Drawable, color: Int) :Drawable {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            drawable.colorFilter = BlendModeColorFilter(color, BlendMode.SRC_ATOP)
            return drawable
        } else {
            drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
            return drawable
        }
    }

수많은 솔루션이 있지만 아무도 컬러 리소스 xml 파일에 이미 컬러가 있으면 아래와 같이 직접 선택할 수 있다고 제안하지 않았습니다.

ImageView imageView = (ImageView) findViewById(R.id.imageview);
imageView.setColorFilter(getString(R.color.your_color));

이 기능은 모든 배경에서 작동합니다.

텍스트 보기, 단추...

TextView text = (TextView) View.findViewById(R.id.MyText);
text.setBackgroundResource(Icon);    
text.getBackground().setColorFilter(getResources().getColor(Color), PorterDuff.Mode.SRC_ATOP);

방금 문제를 발견하고 교체하여 해결했습니다.

android:tint="@color/yellow_800"

이하에

app:tint="@color/yellow_800"

이 샘플 코드 "ColorMatrix Sample.java"를 확인하십시오.

/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.apis.graphics;

import com.example.android.apis.R;

import android.app.Activity;
import android.content.Context;
import android.graphics.*;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;

public class ColorMatrixSample extends GraphicsActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new SampleView(this));
    }

    private static class SampleView extends View {
        private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        private ColorMatrix mCM = new ColorMatrix();
        private Bitmap mBitmap;
        private float mSaturation;
        private float mAngle;

        public SampleView(Context context) {
            super(context);

            mBitmap = BitmapFactory.decodeResource(context.getResources(),
                                                   R.drawable.balloons);
        }

        private static void setTranslate(ColorMatrix cm, float dr, float dg,
                                         float db, float da) {
            cm.set(new float[] {
                   2, 0, 0, 0, dr,
                   0, 2, 0, 0, dg,
                   0, 0, 2, 0, db,
                   0, 0, 0, 1, da });
        }

        private static void setContrast(ColorMatrix cm, float contrast) {
            float scale = contrast + 1.f;
               float translate = (-.5f * scale + .5f) * 255.f;
            cm.set(new float[] {
                   scale, 0, 0, 0, translate,
                   0, scale, 0, 0, translate,
                   0, 0, scale, 0, translate,
                   0, 0, 0, 1, 0 });
        }

        private static void setContrastTranslateOnly(ColorMatrix cm, float contrast) {
            float scale = contrast + 1.f;
               float translate = (-.5f * scale + .5f) * 255.f;
            cm.set(new float[] {
                   1, 0, 0, 0, translate,
                   0, 1, 0, 0, translate,
                   0, 0, 1, 0, translate,
                   0, 0, 0, 1, 0 });
        }

        private static void setContrastScaleOnly(ColorMatrix cm, float contrast) {
            float scale = contrast + 1.f;
               float translate = (-.5f * scale + .5f) * 255.f;
            cm.set(new float[] {
                   scale, 0, 0, 0, 0,
                   0, scale, 0, 0, 0,
                   0, 0, scale, 0, 0,
                   0, 0, 0, 1, 0 });
        }

        @Override protected void onDraw(Canvas canvas) {
            Paint paint = mPaint;
            float x = 20;
            float y = 20;

            canvas.drawColor(Color.WHITE);

            paint.setColorFilter(null);
            canvas.drawBitmap(mBitmap, x, y, paint);

            ColorMatrix cm = new ColorMatrix();

            mAngle += 2;
            if (mAngle > 180) {
                mAngle = 0;
            }

            //convert our animated angle [-180...180] to a contrast value of [-1..1]
            float contrast = mAngle / 180.f;

            setContrast(cm, contrast);
            paint.setColorFilter(new ColorMatrixColorFilter(cm));
            canvas.drawBitmap(mBitmap, x + mBitmap.getWidth() + 10, y, paint);

            setContrastScaleOnly(cm, contrast);
            paint.setColorFilter(new ColorMatrixColorFilter(cm));
            canvas.drawBitmap(mBitmap, x, y + mBitmap.getHeight() + 10, paint);

            setContrastTranslateOnly(cm, contrast);
            paint.setColorFilter(new ColorMatrixColorFilter(cm));
            canvas.drawBitmap(mBitmap, x, y + 2*(mBitmap.getHeight() + 10),
                              paint);

            invalidate();
        }
    }
}

관련 API는 여기에서 이용할 수 있습니다.

다음에 따라 그리기 가능한 색상을 변경하는 간단한 예isWorking들판.

내 모양 xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="@android:color/holo_blue_bright" />
    <corners android:radius="30dp" />
    <size
        android:height="15dp"
        android:width="15dp" />
</shape>

변경 방법:

private Drawable getColoredDrawable(int drawableResId, boolean isworking) {
    Drawable d = getResources().getDrawable(R.drawable.shape);
    ColorFilter filter = new LightingColorFilter(
            isworking ? Color.GREEN : Color.RED,
            isworking ? Color.GREEN : Color.RED);
    d.setColorFilter(filter);
    return d;
}

사용 예:

text1.setCompoundDrawablesWithIntrinsicBounds(getColoredDrawable(R.drawable.shape, isworking()), null, null, null);
Int color = Color.GRAY; 
// or int color = Color.argb(123,255,0,5);
// or int color = 0xaaff000;

XML/res/values/color.xml에서

<?xml version="1.0" encoding="utf-8">
<resources>
    <color name="colorRed">#ff0000</color>
</resoures> 

자바 코드

int color = ContextCompat.getColor(context, R.color.colorRed);

GradientDrawable drawableBg = yourView.getBackground().mutate();
drawableBg.setColor(color);

간단한 드로잉에도 효과가 있습니다.저는 모서리가 둥근 단순한 단색 직모 형태로 사용했고 그 색상을 다른 레이아웃으로 변경해야 했습니다.

이거 먹어봐요.

android:backgroundTint="#101010"

안드로이드 시도:backgroundTint="@color/quantum_black_100"

뷰 바인딩을 사용한 콜틴 용액:

binding.avatar.drawable.colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(R.color.white, BlendModeCompat.SRC_ATOP)

이것은 코어 안드로이드x 라이브러리의 최신 버전을 사용합니다.

Drawable의 색상을 완전히 바꾸고 싶은 사람들에게 도움을 줄 것입니다.

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/ic_memory"
    android:backgroundTint="@color/lime" />

테스트를 해봤습니다. 이것은toArgb()

val drawableIcon = ContextCompat.getDrawable(context, R.drawable.ic_brush);
drawableIcon.setTint(Color.Red.toArgb())

도서관을 이용하면 아주 간단합니다.라이브러리를 사용해 보십시오.

다음과 같이 전화할 수 있습니다.

Icon.on(holderView).color(R.color.your_color).icon(R.mipmap.your_icon).put();

언급URL : https://stackoverflow.com/questions/1309629/how-to-change-colors-of-a-drawable-in-android