安卓 ImageView 投影效果

13

我正在尝试向ImageView添加一个下拉阴影。其他Stackoverflow答案似乎使用画布和位图等方式,比它需要的要复杂得多。

在iOS上,我会这样做:

myImageView.layer.shadowColor = [UIColor redColor].CGColor;
myImageView.layer.shadowRadius = 5;
myImageView.layer.shadowOffset = CGRectMake(0, 5);

不管是在视图、图片还是文本上应用阴影,它都会呈现出一个下拉阴影效果。

我尝试在Android上做同样的事情,但它却无法正常工作:

birdImageView = new ImageView(context);
birdImageView.setImageResource(R.drawable.yellow_bird);

Paint paint = new Paint();
paint.setAntiAlias(true);


birdImageView.setLayerType(LAYER_TYPE_SOFTWARE, null);
paint.setShadowLayer(5, 0, 5, Color.argb(255, 255, 0, 0));
birdImageView.setLayerPaint(paint);

我在鸟的图像上没有看到任何预期的红色投影阴影。

我做错了什么吗?

示例

假设我想要这样的投影阴影:

drop shadow example

更新

我必须使用Android 5.0和新的Elevation API (http://developer.android.com/training/material/shadows-clipping.html) 吗?

但是,如果使用新API,根据当前人口统计数据 (http://www.droid-life.com/2016/02/02/android-distribution-february-2016/) 超过50%的用户将无法使用该应用程序。

T_T


你想要为ImageView或Image添加阴影吗? - Maheshwar Ligade
有关紧密相关的内容,是否很重要?无论应用在什么上面,投影API都应该能够正常工作。我已经附上了一个投影效果的示例图像。 - Zhang
1个回答

7
在Android Studio中,有一个内置的drawable可以用于对任何View应用阴影。这类似于一个投影。
android:background="@drawable/abc_menu_dropdown_panel_holo_light"

使用这个方法无法更改视图的背景颜色和边框颜色。如果你想要自定义的drawable,那么请使用layer-list

custom_drop_shadow_drawable.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!--the shadow comes from here-->
    <item
        android:bottom="0dp"
        android:drawable="@android:drawable/dialog_holo_light_frame"
        android:left="0dp"
        android:right="0dp"
        android:top="0dp">

    </item>

    <item
        android:bottom="0dp"
        android:left="0dp"
        android:right="0dp"
        android:top="0dp">
        <!--whatever you want in the background -->
        <shape android:shape="rectangle">
            <solid android:color="@android:color/red" />

        </shape>
    </item>
</layer-list>

并将其应用到以下视图中。
android:background="@drawable/custom_drop_shadow_drawable"

希望能对你有所帮助!感谢Android View shadow


4
你至少应该给原回答注明出处——https://dev59.com/4GEi5IYBdhLWcg3whccg#33889791。 - ClassA
7
这个物体会投出一个矩形的阴影,不是像上面那样在图像周围产生阴影。 - Nizamudeen Sherif

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接