css 如何为ImageButton添加阴影?

af7jpaap  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(55)

这是我第一次发帖。我一直在使用这个网站作为一个很好的资源。但我遇到了一个问题。我已经尝试应用阴影效果到我的ImageButton,但它doest工作?我试图实现的是阴影,你可以看到浮动的气泡(材料设计)。我有一个圆形ImageButton,但我想添加一个阴影周围。我如何才能实现这一点?
这是circle_button. xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#C62666"/>
</shape>

字符串
这是circle_button_pressed. xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#E92D6C"/>
</shape>


这是我的选择器,它将两个drawable合并为一个。button.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/circle_button"
        android:state_focused="true"
        android:state_pressed="true" />
    <item android:drawable="@drawable/circle_button_pressed"
        android:state_focused="false"
        android:state_pressed="true" />
    <item android:drawable="@drawable/circle_button_pressed"
            android:state_focused="true" />
    <item android:drawable="@drawable/circle_button"
        android:state_focused="false"
        android:state_pressed="false" />
</selector>


这就是我如何将它应用到我的ImageButton中

<ImageButton
           android:id="@+id/btn_apply"
           android:layout_width="68dp"
           android:layout_height="68dp"
           android:layout_alignParentTop="true"
           android:layout_alignRight="@+id/scrollView1"
           android:layout_marginRight="45dp"
           android:layout_marginTop="94dp"
           android:adjustViewBounds="true"
           android:background="@drawable/button"
           android:scaleType="fitCenter"
           android:src="@drawable/apply_two" />


又来了?我怎么能给我的按钮添加阴影呢?谢谢你的时间。

qoefvg9y

qoefvg9y1#

你可以使用一个elevation和一个带阴影的背景绘图的组合。下面是你如何修改你的ImageButton来实现这个效果:首先,将你的ImageButton包裹在CardView中以利用elevation属性,它会自动添加一个阴影。

<androidx.cardview.widget.CardView
    android:id="@+id/cardView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    app:cardCornerRadius="34dp" <!-- it should be half of your button's width or height -->
    app:cardElevation="8dp">

    <ImageButton
        android:id="@+id/btn_apply"
        android:layout_width="68dp"
        android:layout_height="68dp"
        android:layout_gravity="center"
        android:adjustViewBounds="true"
        android:scaleType="fitCenter"
        android:src="@drawable/apply_two"
        android:background="@null" />
</androidx.cardview.widget.CardView>

字符串
其次,确保在build.gradle文件中添加CardView依赖项:

implementation 'androidx.cardview:cardview:1.0.0'


第三,调整layout_width、layout_height和app:cardCornerRadius值以适合您的设计。app:cardCornerRadius应该是按钮宽度或高度的一半,以创建圆形形状。
最后,从ImageButton中删除android:background="@drawable/button”属性,以允许CardView处理阴影。

相关问题