5

我正在尝试以编程方式制作具有不同渐变的按钮。我使用 ShapeDrawable,它就像一个魅力。

RoundRectShape rs = new RoundRectShape(new float[] { 12f, 12f, 12f, 12f, 12f, 12f, 12f, 12f }, null, null);
ShapeDrawable sd = new ShapeDrawable(rs);
ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {

    @Override
    public Shader resize(int width, int height) {
        LinearGradient lg = new LinearGradient(0, 0, 0, height,
                new int[] { 
                    Color.parseColor("#feccb1"), 
                    Color.parseColor("#f17432"), 
                    Color.parseColor("#e86320"),
                    Color.parseColor("#f96e22") },
                new float[] {
                    0, 0.50f, 0.50f, 1 },
                Shader.TileMode.REPEAT);
             return lg;
        }
    };
sd.setShaderFactory(sf);
myBtn.setBackgroundDrawable(sd);

但是我想以编程方式为按钮添加阴影而不是按钮文本。任何帮助,将不胜感激。

4

2 回答 2

8

但是我想以编程方式为按钮添加阴影,而不是按钮文本。

我猜你想要你构建的当前drawable背后的阴影。如果是,则将 aLayerDrawable与另一个Drawable(放置在第一位)一起作为阴影:

    RoundRectShape rss = new RoundRectShape(new float[] { 12f, 12f, 12f,
            12f, 12f, 12f, 12f, 12f }, null, null);
    ShapeDrawable sds = new ShapeDrawable(rss);
    sds.setShaderFactory(new ShapeDrawable.ShaderFactory() {

        @Override
        public Shader resize(int width, int height) {
            LinearGradient lg = new LinearGradient(0, 0, 0, height,
                    new int[] { Color.parseColor("#e5e5e5"),
                            Color.parseColor("#e5e5e5"),
                            Color.parseColor("#e5e5e5"),
                            Color.parseColor("#e5e5e5") }, new float[] { 0,
                            0.50f, 0.50f, 1 }, Shader.TileMode.REPEAT);
            return lg;
        }
    });

    LayerDrawable ld = new LayerDrawable(new Drawable[] { sds, sd });
    ld.setLayerInset(0, 5, 5, 0, 0); // inset the shadow so it doesn't start right at the left/top
    ld.setLayerInset(1, 0, 0, 5, 5); // inset the top drawable so we can leave a bit of space for the shadow to use

    b.setBackgroundDrawable(ld);
于 2012-12-26T19:21:01.650 回答
-1

一种更干净的方法是使用杰克的Paint.setShadowLayer回答

于 2017-06-16T16:37:13.280 回答