繁体   English   中英

以编程方式向ShapeDrawable添加阴影

[英]Add shadow to the ShapeDrawable programmatically

我试图以编程方式制作具有不同渐变的按钮。 我使用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);

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

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

我想你想要建立你当前绘制的阴影。 如果是,则将LayerDrawable与另一个将作为阴影的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);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM