繁体   English   中英

背景设置为可绘制时如何从Button获取颜色

[英]How to get color from Button when background set as drawable

我有一个<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获取颜色?

采用:

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

尝试:

val color = (btn.background as? ShapeDrawable)?.paint.color

为什么不将Drawable转换为Bitmap(链接: 如何将Drawable转换为Bitmap? ),然后将Pixel置于其中心? 可能不是最快的方法,而是最兼容的方法之一(因为“渐变”,“颜色”或其他类型的“可绘制”都被展平为兼容的位图,并且您无需处理这些差异)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM