java - 以编程方式向 ShapeDrawable 添加阴影

标签 java android shadow shapedrawable

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

不过,我想以编程方式向按钮添加一个阴影不是按钮文本。任何帮助将不胜感激。

最佳答案

However I would like to add a shadow to the button, not the button text programmatically.

我猜你想要你构建的当前可绘制对象后面的阴影。如果是,则制作 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);

关于java - 以编程方式向 ShapeDrawable 添加阴影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14042251/

相关文章:

Java MessageDigest 与 iOS CCHmac-sha256

java - 在命令行中执行 headless eclipse

Android:如何检查应用程序是否已进入后台以避免不需要的 BroadcastReceiver 检查

c++ - 阴影贴图透视别名

java - Weblogic 12 hibernate 验证异常

Java GetFile 在使用 SetFile 后返回不正确的文件名

android - Espresso AutoCompleteTextView 点击

android - 当设备处于横向时拍摄人像照片有问题吗?

ios - 在 iOS 中,alpha 为 0.5 的 shadowColor 和设置为 0.5 的 shadowOpacity 有区别吗?

shadow - 使用框阴影使 div 看起来好像左下角和右下角稍微离开页面?