programing

Android Studio에서 벡터 자산의 채우기 색 변경

jooyons 2023. 10. 22. 20:02
반응형

Android Studio에서 벡터 자산의 채우기 색 변경

Android Studio는 이제 21+에서 벡터 자산을 지원하며 컴파일 시 하위 버전을 위한 png를 생성합니다.채우기 색상을 변경할 벡터 자산(Material Icons(재료 아이콘))이 있습니다.이것은 21+에서 작동하지만 생성된 pngs는 색상이 변하지 않습니다.이것을 할 방법이 방법이 있습니까?

<vector android:height="48dp" android:viewportHeight="24.0"
android:viewportWidth="24.0" android:width="48dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="@color/primary" android:pathData="M9,16.17L4.83,12l-1.42,1.41L9,19 21,7l-1.41,-1.41z"/>

벡터 자산을 직접 편집하지 마십시오.ImageButton(이미지 버튼)에서 그릴 수 있는 벡터를 사용하는 경우, 다음에서 색상을 선택합니다.android:tint.

<ImageButton
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:id="@+id/button"
        android:src="@drawable/ic_more_vert_24dp"
        android:tint="@color/primary" />

당신은 할 수 있어요.

그러나 색상에 @color references(..lame)를 사용할 수 없습니다. 그렇지 않으면 L+에서만 작동합니다.

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0">
<path
    android:fillColor="#FFAABB"
    android:pathData="M15.5,14h-0.79l-0.28,-0.27C15.41,12.59 16,11.11 16,9.5 16,5.91 13.09,3 9.5,3S3,5.91 3,9.5 5.91,16 9.5,16c1.61,0 3.09,-0.59 4.23,-1.57l0.27,0.28v0.79l5,4.99L20.49,19l-4.99,-5zm-6,0C7.01,14 5,11.99 5,9.5S7.01,5 9.5,5 14,7.01 14,9.5 11.99,14 9.5,14z"/>

다른 답변에서도 말했듯이, 벡터 드로잉 가능한 것을 직접 편집하지 말고, 자바 코드로 틴트 할 수 있습니다.

    mWrappedDrawable = mDrawable.mutate();
    mWrappedDrawable = DrawableCompat.wrap(mWrappedDrawable);
    DrawableCompat.setTint(mWrappedDrawable, mColor);
    DrawableCompat.setTintMode(mWrappedDrawable, PorterDuff.Mode.SRC_IN);

단순화를 위해 도우미 클래스를 만들었습니다.

import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

/**
 * {@link Drawable} helper class.
 *
 * @author Filipe Bezerra
 * @version 18/01/2016
 * @since 18/01/2016
 */
public class DrawableHelper {
    @NonNull Context mContext;
    @ColorRes private int mColor;
    private Drawable mDrawable;
    private Drawable mWrappedDrawable;

    public DrawableHelper(@NonNull Context context) {
        mContext = context;
    }

    public static DrawableHelper withContext(@NonNull Context context) {
        return new DrawableHelper(context);
    }

    public DrawableHelper withDrawable(@DrawableRes int drawableRes) {
        mDrawable = ContextCompat.getDrawable(mContext, drawableRes);
        return this;
    }

    public DrawableHelper withDrawable(@NonNull Drawable drawable) {
        mDrawable = drawable;
        return this;
    }

    public DrawableHelper withColor(@ColorRes int colorRes) {
        mColor = ContextCompat.getColor(mContext, colorRes);
        return this;
    }

    public DrawableHelper tint() {
        if (mDrawable == null) {
            throw new NullPointerException("É preciso informar o recurso drawable pelo método withDrawable()");
        }

        if (mColor == 0) {
            throw new IllegalStateException("É necessário informar a cor a ser definida pelo método withColor()");
        }

        mWrappedDrawable = mDrawable.mutate();
        mWrappedDrawable = DrawableCompat.wrap(mWrappedDrawable);
        DrawableCompat.setTint(mWrappedDrawable, mColor);
        DrawableCompat.setTintMode(mWrappedDrawable, PorterDuff.Mode.SRC_IN);

        return this;
    }

    @SuppressWarnings("deprecation")
    public void applyToBackground(@NonNull View view) {
        if (mWrappedDrawable == null) {
            throw new NullPointerException("É preciso chamar o método tint()");
        }

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            view.setBackground(mWrappedDrawable);
        } else {
            view.setBackgroundDrawable(mWrappedDrawable);
        }
    }

    public void applyTo(@NonNull ImageView imageView) {
        if (mWrappedDrawable == null) {
            throw new NullPointerException("É preciso chamar o método tint()");
        }

        imageView.setImageDrawable(mWrappedDrawable);
    }

    public void applyTo(@NonNull MenuItem menuItem) {
        if (mWrappedDrawable == null) {
            throw new NullPointerException("É preciso chamar o método tint()");
        }

        menuItem.setIcon(mWrappedDrawable);
    }

    public Drawable get() {
        if (mWrappedDrawable == null) {
            throw new NullPointerException("É preciso chamar o método tint()");
        }

        return mWrappedDrawable;
    }
}

사용하려면 다음 작업만 수행합니다.

    DrawableHelper
            .withContext(this)
            .withColor(R.color.white)
            .withDrawable(R.drawable.ic_search_24dp)
            .tint()
            .applyTo(mSearchItem);

또는:

    final Drawable drawable = DrawableHelper
            .withContext(this)
            .withColor(R.color.white)
            .withDrawable(R.drawable.ic_search_24dp)
            .tint()
            .get();

    actionBar.setHomeAsUpIndicator(drawable);

벡터 이미지 색상을 변경하려면 안드로이드:tint="@color/colorAccent"를 직접 사용하면 됩니다.

<ImageView
        android:id="@+id/ivVectorImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_account_circle_black_24dp"
        android:tint="@color/colorAccent" />

프로그래밍 방식으로 색을 변경하려면

ImageView ivVectorImage = (ImageView) findViewById(R.id.ivVectorImage);
ivVectorImage.setColorFilter(getResources().getColor(R.color.colorPrimary));

현재 작업 솔루션은 안드로이드:fillColor="#FFFFFF"입니다.

벡터에서 하드 코딩하는 것 외에는 아무것도 나에게 통하지 않았습니다.

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
      android:fillColor="#FFFFFF"
    android:viewportHeight="24.0">
<path
    android:fillColor="#FFFFFF"
    android:pathData="M15.5,14h-0.79l-0.28,-0.27C15.41,12.59 16,11.11 16,9.5 16,5.91 13.09,3 9.5,3S3,5.91 3,9.5 5.91,16 9.5,16c1.61,0 3.09,-0.59 4.23,-1.57l0.27,0.28v0.79l5,4.99L20.49,19l-4.99,-5zm-6,0C7.01,14 5,11.99 5,9.5S7.01,5 9.5,5 14,7.01 14,9.5 11.99,14 9.5,14z"/>

하지만 필 컬러와 틴트는 곧 효과가 있을지도 모릅니다.자세한 내용은 이 토론을 참조하시기 바랍니다.

https://code.google.com/p/android/issues/detail?id=186431

또한 캐시에 색이 묻어있을 수 있으므로 모든 사용자의 앱을 삭제하는 것이 도움이 될 수 있습니다.

업데이트:AppCompat지지하다

다른 대답들은 의심하고 있습니다.android:tint21개 이상의 장치에서만 작동합니다. AppCompat(v23.2.0 이상)은 틴트 속성의 하위 호환 처리를 제공합니다.

그래서, 행동 방침은 다음과 같은 것을 사용하는 것일 것입니다.AppCompatImageView그리고.app:srcCompat(AppCompat 네임스페이스에서) 대신android:src(안드로이드 네임스페이스).

다음은 예시입니다(Android X:안드로이드x.appcompat 입니다.위젯.AppCompat ImageView ;):

<android.support.v7.widget.AppCompatImageView
        android:id="@+id/credits_material_icon"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"
        android:scaleType="fitCenter"
        android:tint="#ffd2ee"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:srcCompat="@drawable/ic_dollar_coin_stack" />

그리고 그래들에서 벡터를 그릴 수 있는 지원을 활성화하는 것을 잊지 마십시오.

vectorDrawables.useSupportLibrary = true 

안드로이드 스튜디오는 이제 벡터 프리롤리팝을 지원합니다.PNG 변환 금지.채움 색상을 변경할 수 있으며, 사용할 수 있습니다.

In you ImageView, 사용

 app:srcCompat="@drawable/ic_more_vert_24dp"

그래들 파일에서

 // Gradle Plugin 2.0+  
 android {  
   defaultConfig {  
     vectorDrawables.useSupportLibrary = true  
   }  
 }  

 compile 'com.android.support:design:23.4.0'
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="//Your Color Code//">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M11,9.16V2c-5,0.5 -9,4.79 -9,10s4,9.5 9"/>
</vector>

벡터가 fillColor를 사용하여 개별적으로 설정된 색상을 표시하지 않는 경우 기본 위젯 파라미터로 설정될 수 있습니다.

추가해 보기app:itemIconTint="@color/lime"activity_main.xml로 위젯 아이콘의 기본 색상 유형을 설정합니다.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:itemIconTint="@color/lime"
        app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>

VectorDrawable @ developers.an 드로이드

이 라이브러리를 그라들에 추가하면 이전 안드로이드 장치에서 그릴 수 있는 색 벡터를 사용할 수 있습니다.

compile 'com.android.support:palette-v7:26.0.0-alpha1'

그라들을 다시 동기화합니다.그것이 그 문제를 해결해 줄 것이라고 생각합니다.

이전 버전의 prelolipop을 지원하려고 한다면,

몇 가지 변경 사항이 있는 동일한 xml 코드를 사용합니다.

보통이 아닌ImageView --> AppCompatImageView

대신에android:src --> app:srcCompat

여기 예시가 있습니다.

<android.support.v7.widget.AppCompatImageView
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:id="@+id/button"
        app:srcCompat="@drawable/ic_more_vert_24dp"
        android:tint="@color/primary" />

@ Sayooj Valsan mention처럼 gradle을 업데이트하는 것을 잊지 마세요.

// Gradle Plugin 2.0+  
 android {  
   defaultConfig {  
     vectorDrawables.useSupportLibrary = true  
   }  
 }  

 compile 'com.android.support:design:23.4.0'

어느 누구에게도 벡터를 사용하는 사람은 절대로 이와 같은 색상에 대한 벡터 참조를 주지 마십시오.android:fillColor="@color/primary"16분의 1의 값을

MainActivity.java로 이동하고 이 코드 아래로 이동합니다.
->NavigationView navigationView = findViewById(R.id.nav_view);
단일 줄 코드 추가 ->navigationView.setItemIconTintList(null);
내 코드의 마지막 줄

이것이 당신의 문제를 해결할 수 있기를 바랍니다.

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setItemIconTintList(null);

ImageButton(이미지 버튼)의 경우,app:tint="@color/green"대신에android:tint

사용하지 않는 사람들을 위해ImageView, 평원에서 나는 다음과 같은 일을 했습니다.View(따라서 행동은 어떤 종류의 관점에서도 복제되어야 합니다.)

<View
    android:background="@drawable/ic_reset"
    android:backgroundTint="@color/colorLightText" />

항목 벡터 아이콘의 색상을 변경하려면 다음을 사용할 수 있습니다.

android:iconTint="@color/color"

벡터 자산이 CardView(카드 뷰) 내에 있으면 시도해 봅니다.card_view:tint="@color/secondary"이미지 보기 내에 표시됩니다.참고: 바꾸기@color/secondary원하시는 색상으로

사용하다

android:drawableTint="@color/primary"

inactivity_main.xml

activity_main.xml

Drawable Helper의 Kotlin 버전은 다음과 같습니다.Filipe

class DrawableHelper(var mContext: Context) {
    @ColorRes
    private var mColor = 0
    private lateinit var mDrawable: Drawable
    private lateinit var mWrappedDrawable: Drawable
    fun withDrawable(@DrawableRes drawableRes: Int): DrawableHelper {
        mDrawable = getDrawable(mContext, drawableRes)!!
        return this
    }

    fun withDrawable(drawable: Drawable): DrawableHelper {
        mDrawable = drawable
        return this
    }

    @SuppressLint("ResourceType")
    fun withColor(@ColorRes colorRes: Int): DrawableHelper {
        mColor = ContextCompat.getColor(mContext, colorRes)
        return this
    }

    @SuppressLint("ResourceAsColor")
    fun tint(): DrawableHelper {
        mWrappedDrawable = DrawableCompat.wrap(mWrappedDrawable)
        DrawableCompat.setTint(mWrappedDrawable, mColor)
        DrawableCompat.setTintMode(mWrappedDrawable, PorterDuff.Mode.SRC_IN)
        return this
    }

    fun applyToBackground(view: View) {
        view.background = mWrappedDrawable
    }

    fun applyTo(imageView: ImageView) {
        imageView.setImageDrawable(mWrappedDrawable)
    }

    fun applyTo(menuItem: MenuItem) {
        menuItem.icon = mWrappedDrawable
    }

    fun get(): Drawable {
        return mWrappedDrawable
    }

    companion object {
        fun withContext(context: Context): DrawableHelper {
            return DrawableHelper(context)
        }
    }
}

언급URL : https://stackoverflow.com/questions/32924986/change-fill-color-on-vector-asset-in-android-studio

반응형