Android:如何使用 XML drawable 创建精确的材料设计阴影

Posted

技术标签:

【中文标题】Android:如何使用 XML drawable 创建精确的材料设计阴影【英文标题】:Android: How to create exact material design shadow with XML drawable 【发布时间】:2017-06-08 18:48:54 【问题描述】:

我想制作一个 XMl 可绘制文件,该文件尽可能类似于 Lollipop 及更高版本上的材料设计立面图。我目前有一个甚至没有接近的阴影,因为我不知道我应该使用什么渐变。

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape android:shape="rectangle">
        <gradient android:angle="90"
            android:endColor="@android:color/darker_gray" 
            android:startColor="#ccc" />
        <corners android:radius="0.1dp"
            android:bottomLeftRadius="3dp"
            android:bottomRightRadius="3dp"
            android:topLeftRadius="3dp"
            android:topRightRadius="3dp"/>
    </shape>
</item>
<item
    android:left="1.5dp"
    android:right="1.5dp"
    android:top="1.5dp"
    android:bottom="1.5dp">

    <shape android:shape="rectangle">

<solid android:color="@android:color/white" />

<corners
    android:radius="0.1dp"
    android:bottomLeftRadius="3dp"
    android:bottomRightRadius="3dp"
    android:topLeftRadius="3dp"
    android:topRightRadius="3dp" />
</shape>
</item>
</layer-list>

有人能想出一个至少比我更好的解决方案吗?谢谢。

【问题讨论】:

exact material design 是什么意思? 就我而言,我希望搜索栏的阴影尽可能接近第一张图片。 嗯,不,这和那个帖子不一样。 我在问如何使用可绘制文件创建这种效果。 阅读this 【参考方案1】:

为了完美的阴影使用 CardView

Xamarin:MSDN Source

在 Visual Studio 中添加 Xamarin.Android.Support.v7.CardView 包

<android.support.v7.widget.CardView
          xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:local="http://schemas.android.com/apk/res-auto"
          android:layout_
          android:layout_
          android:layout_margin="@dimen/shrine_grid_item_margin"
          android:orientation="vertical"
          local:cardElevation="@dimen/cardview_default_elevation">
<!-- Content Goes here-->
</android.support.v7.widget.CardView>

或者

Android:Android Devs Source

CardView 小部件是 v7 支持库的一部分。要在您的项目中使用它,请将以下依赖项添加到您的应用模块的 build.gradle 文件中:

dependencies 
    implementation 'com.android.support:cardview-v7:28.0.0'

XXX

<androidx.cardview.widget.CardView
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:id="@+id/ProductEntry"
  android:layout_
  android:layout_
  android:layout_margin="@dimen/shrine_grid_item_margin"
  android:orientation="vertical"
  app:cardElevation="@dimen/cardview_default_elevation">
<!-- Content Goes here-->
</androidx.cardview.widget.CardView>

【讨论】:

【参考方案2】:

您需要在布局资源文件中定义高程以放置阴影。 在您的 layout.xml 文件中,它应该看起来像这样

<TextView
    android:id="@+id/myview"
    android:elevation="2dp"
    android:background="@drawable/myrect" />

【讨论】:

OP 不要求TextView

以上是关于Android:如何使用 XML drawable 创建精确的材料设计阴影的主要内容,如果未能解决你的问题,请参考以下文章

Android - 使用 xml drawable 制作检查图标

如何将 Android XML Drawable 保存、导出或转换为 PNG 图像文件?

Android Drawable - Shape Drawable使用详解(附图)

如何在android中的drawable上添加阴影效果

Android入门——Drawable与对应的资源xml的应用

如何在Android drawable中为环形制作圆角