如何从GradientDrawable中获取颜色

时间:2014-10-22 06:11:19

标签: android

首先,我将绿色设置为View mIcon的背景,

View mIcon = findViewById(R.id.xxx);

GradientDrawable gdraw = (GradientDrawable) mContext.getResources().getDrawable(R.drawable.roundbtn_white_normal);
gdraw.setColor(Color.GREEN);
mIcon.setBackgroundDrawable(gdraw);

然后,我不知道如何从这个View的背景中获取颜色......没有getColor() 功能...

3 个答案:

答案 0 :(得分:4)

到目前为止,以下课程对我来说很合适。

import android.content.res.Resources;
...

// it's the same with the GradientDrawable, just make some proper modification to make it compilable
public class ColorGradientDrawable extends Drawable {
    ...
    private int mColor; // this is the color which you try to get
    ...
    // original setColor function with little modification
    public void setColor(int argb) {
        mColor = argb;
        mGradientState.setSolidColor(argb);
        mFillPaint.setColor(argb);
        invalidateSelf();
    }

    // that's how I get the color from this drawable class
    public int getColor() {
        return mColor;
    }
    ...

    // it's the same with GradientState, just make some proper modification to make it compilable
    final public static class GradientState extends ConstantState {
        ...
    }
}

答案 1 :(得分:3)

  

getColor()API被添加到API 24中的渐变可绘制类中。

https://developer.android.com/reference/android/graphics/drawable/GradientDrawable.html

答案 2 :(得分:1)

如果你的背景是纯色,这只能在API 11+中完成。 将它作为Drawable轻松搞定

Drawable mIconBackground = mIcon.getBackground();         
if (mIconBackground instanceof ColorDrawable)
            color = ((ColorDrawable) background).getColor();

如果您使用的是Android 3.0+,则可以获得该颜色的资源ID。

int colorId = mIcon.getColor();

并将其与指定的颜色进行比较,即

if (colorId == Color.GREEN) {
  log("color is green");
}

希望这会对你有所帮助。