Android在视图上投下阴影

时间:2010-08-25 15:05:48

标签: android xml imageview shadow dropshadow

我已经对此进行了一些广泛的代码搜索示例,但找不到任何内容。

特别是,我希望为我在ImageView中使用的png drawable添加阴影。这个png drawable是一个带有透明角的圆角矩形。

有人可以提供一个代码示例,说明如何在代码或XML中为视图添加一个不错的投影?

5 个答案:

答案 0 :(得分:32)

您可以使用Bitmap.extractAlpha和BlurMaskFilter的组合为您需要显示的任何图像手动创建投影,但这仅适用于您的图像仅偶尔加载/显示一次,因为该过程很贵。

伪代码(甚至可以编译!):

BlurMaskFilter blurFilter = new BlurMaskFilter(5, BlurMaskFilter.Blur.OUTER);
Paint shadowPaint = new Paint();
shadowPaint.setMaskFilter(blurFilter);

int[] offsetXY = new int[2];
Bitmap shadowImage = originalBitmap.extractAlpha(shadowPaint, offsetXY);

/* Might need to convert shadowImage from 8-bit to ARGB here, can't remember. */

Canvas c = new Canvas(shadowImage);
c.drawBitmap(originalBitmap, offsetXY[0], offsetXY[1], null);

然后将shadowImage放入ImageView。如果此图像永远不会改变但显示很多,您可以创建它并将其缓存在onCreate中以绕过昂贵的图像处理。

即使这不起作用,也应该足以让你朝着正确的方向前进。

答案 1 :(得分:26)

对于代码

下的投影使用
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
  <gradient
    android:startColor="#ffffff"
    android:centerColor="#d3d7cf"
    android:endColor="#2e3436"
    android:angle="90" />
</shape>

将上面的drawable用于视图背景

<View 
    android:id="@+id/divider" 
    android:background="@drawable/black_white_gradient"
    android:layout_width="match_parent" 
    android:layout_height="10sp"
    android:layout_below="@+id/buildingsList"/>

答案 2 :(得分:10)

这帮助我让影子工作,所以我想分享工作代码:

private Bitmap createShadowBitmap(Bitmap originalBitmap) {
    BlurMaskFilter blurFilter = new BlurMaskFilter(5, BlurMaskFilter.Blur.OUTER);
    Paint shadowPaint = new Paint();
    shadowPaint.setMaskFilter(blurFilter);

    int[] offsetXY = new int[2];
    Bitmap shadowImage = originalBitmap.extractAlpha(shadowPaint, offsetXY);

    /* Need to convert shadowImage from 8-bit to ARGB here. */
    Bitmap shadowImage32 = shadowImage.copy(Bitmap.Config.ARGB_8888, true);
    Canvas c = new Canvas(shadowImage32);
    c.drawBitmap(originalBitmap, -offsetXY[0], -offsetXY[1], null);

    return shadowImage32;
}

答案 3 :(得分:5)

对于API 21(5.0)+ 添加android:elevation="4dp"android:translationZ="4dp"以查看说明。 Documentation

Elevation Attribute

答案 4 :(得分:1)

始终使用透明阴影,以便它们可以粘贴任何颜色。

shadow.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
  <gradient
    android:startColor="#002e3436"
    android:endColor="#992e3436"
    android:angle="90" />
</shape>

在视图中

<View 
    android:id="@+id/divider" 
    android:background="@drawable/shadow"
    android:layout_width="match_parent" 
    android:layout_height="5dp"/>