【问题标题】:how to get the color from GradientDrawable如何从 GradientDrawable 获取颜色
【发布时间】:2014-12-17 12:55:21
【问题描述】:

首先,我将绿色设置为 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() 函数...

【问题讨论】:

    标签: android


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      到目前为止,以下课程对我来说效果很好。

      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 {
              ...
          }
      }
      

      【讨论】:

        【解决方案3】:

        这只能在 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");
        }
        

        希望这会对你有所帮助。

        【讨论】:

        • 如你所见 mContext.getResources().getDrawable(R.drawable.roundbtn_white_normal);这会返回一个 GradientDrawable
        猜你喜欢
        • 2020-08-27
        • 1970-01-01
        • 1970-01-01
        • 2012-10-11
        • 1970-01-01
        • 2011-05-09
        • 2018-03-07
        • 2012-06-10
        相关资源
        最近更新 更多