如何以编程方式从图层列表创建阴影效果?

时间:2014-01-30 16:03:49

标签: android

我已经学会了如何使用图层列表为textview / button创建阴影效果。我使用此代码作为参考: -

<?xml version="1.0" encoding="utf-8"?>

                               

        <corners android:radius="15dp" />
    </shape>
</item>
<!-- background color -->
<item
    android:bottom="3px"
    android:left="3px"
    android:right="3px"
    android:top="3px">
    <shape android:shape="rectangle" >
        <solid android:color="#cc2b2b" />


        <corners android:radius="8dp" />
    </shape>
</item>
<!-- over left shadow -->
<item>
    <shape android:shape="rectangle" >
        <gradient
            android:angle="180"
            android:centerColor="#00FF0000"
            android:centerX="0.9"
            android:endColor="#99000000"
            android:startColor="#00FF0000" />

        <corners android:radius="8dp" />
    </shape>
</item>
<!-- over right shadow -->
<item>
    <shape android:shape="rectangle" >
        <gradient
            android:angle="360"
            android:centerColor="#00FF0000"
            android:centerX="0.9"
            android:endColor="#99000000"
            android:startColor="#00FF0000" />

        <corners android:radius="8dp" />
    </shape>
</item>
<!-- over top shadow -->
<item>
    <shape android:shape="rectangle" >
        <gradient
            android:angle="-90"
            android:centerColor="#00FF0000"
            android:centerY="0.9"
            android:endColor="#00FF0000"
            android:startColor="#99000000"
            android:type="linear" />

        <corners android:radius="8dp" />
    </shape>
</item>
<!-- over bottom shadow -->
<item>
    <shape android:shape="rectangle" >
        <gradient
            android:angle="90"
            android:centerColor="#00FF0000"
            android:centerY="0.9"
            android:endColor="#00FF0000"
            android:startColor="#99000000"
            android:type="linear" />

        <corners android:radius="8dp" />
    </shape>
</item>

enter image description here

我想知道如何使用Layer Drawable / Gradient Drawable动态实现这一目标? 任何建议

1 个答案:

答案 0 :(得分:1)

这将是一个痛苦的缓慢过程,但肯定是完全可能的,它只是遵循XML的确实:

// create the layers
Drawable[] layer = new Drawable[5] // or whatever amount in the XML

// build the layers
layer[0] = new ShapeDrawable();
layer[0]. // call methods here to configure the 1st layer

layer[1] = new ShapeDrawable();
layer[1]. // call methods here to configure the 2nd layer
... etc ...

LayerDrawable layerDrawable = new LayerDrawable(layer);

参考LayerDrawableShapeDrawableDrawables