我有一个<Button/>
<Button
android:id="@+id/btn"
android:background="@drawable/btn_color"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
按钮背景设置为android:background="@drawable/btn_color"
,其中btn_color
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
android:padding="10dp">
<solid android:color="#FF0000"/>
<corners android:radius="10dp"/>
</shape>
我需要在代码中获得按钮的颜色#FF0000
。我尝试过的是
val drawable = btn.getBackground().mutate() as GradientDrawable
如何从此Drawable获取颜色?
答案 0 :(得分:0)
使用:
val color = (btn.background as? GradientDrawable)?.color?.defaultColor
编辑
但getColor()
仅在 API 24及更高版本 上可用。您应该检查Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
:
val color = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
(btn.background as? GradientDrawable)?.color?.defaultColor
} else null
答案 1 :(得分:0)
尝试:
val color = (btn.background as? ShapeDrawable)?.paint.color
答案 2 :(得分:0)
为什么不将Drawable转换为位图(链接:How to convert a Drawable to a Bitmap?),然后将Pixel置于其中心?可能不是最快的方法,而是最兼容的方法之一(因为“渐变”,“颜色”或其他类型的“可绘制”都被展平为兼容的位图,并且您无需处理这些差异)