【问题标题】:How to create a shape with a transparent background and a shadow, but the shadow should not be visible behind the shape outline?如何创建具有透明背景和阴影的形状,但在形状轮廓后面不应该看到阴影?
【发布时间】:2019-06-14 08:14:13
【问题描述】:

这里有点类似的问题,但答案是删除高程和阴影......不是我想要的:Android CardView with weird border when transparent

我想要的是 Pixel Launcher 搜索栏中显示的内容...即具有半透明背景和阴影的形状,但 阴影不与白色形状重叠 (最终会使它看起来是灰色的)。我基本上想要一个阴影,但在我的形状中间有一个洞......

这就是我想要实现的(底部的搜索栏):

这是我尝试过的,但您可以从所附图片中看到,灰色阴影来自半透明的白色背景。

activity_main.xml

    <FrameLayout
      android:layout_width="120dp"
      android:layout_height="120dp"
      android:background="@drawable/rectangle"
      android:elevation="8dp" />

矩形.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android">
  <corners android:radius="4dp" />
  <solid android:color="#aaffffff" />
</shape>

这是我的尝试的样子:

您可以看到,即使我的形状在白色背景上是半透明的白色,它也会因为下面的阴影而变成灰色,这不是我想要的。

我也尝试过使用 View#setOutlineProvider,但没有成功。

我也试过玩https://github.com/harjot-oberai/MaterialShadows

如果可以避免的话,我不想使用 9patch 图像。

【问题讨论】:

  • 你有没有机会在卡片视图上方使用它?
  • 您的布局可以按照您的意愿完美运行。
  • 灰色阴影是使用高程的结果。尝试将海拔值设置为0dp
  • @KaranMer 正确,但这也会消除阴影,这是想要的
  • 您是否尝试过使用较小的海拔值例如2dp?高程值越大,阴影越暗

标签: android transparent shadow


【解决方案1】:

一种解决方案是将透明度应用于框架本身,而不仅仅是矩形的背景。这将产生类似于图中所示的效果。

例如:

<FrameLayout
    android:layout_width="120dp"
    android:layout_height="120dp"
    android:elevation="8dp"
    android:alpha="0.6" />

如果你想要不透明的元素,这当然会有问题,要解决这个问题,你可以提取背景,然后按照以下方式做一些事情:

<FrameLayout
    android:layout_width="120dp"
    android:layout_height="120dp">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/rectangle"
        android:alpha="0.6"
        android:elevation="8dp" />
</FrameLayout>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多