2017-10-11 102 views
2

我有以下梯度更改渐变中心动态

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
<gradient 
    android:angle="90" 
    android:centerColor="#42f448" 
    android:centerX="0.5" 
    android:centerY="0.5" 
    android:endColor="#000000" 
    android:startColor="#000000" 
    android:type="linear" /> 

我需要做的是改变基于一个ListView位置变化的渐变中心。是否有可能以编程方式创建此渐变?

我试过这种方法,但如果我改变中心值,没有任何反应,它保持不变:

int colors[] = {0xff000000, 0xff42f448, 0xff000000}; 
    GradientDrawable shape = new GradientDrawable(); 
    shape.setOrientation(GradientDrawable.Orientation.TOP_BOTTOM); 
    shape.setColors(colors); 
    shape.setGradientCenter(0.3f, 0.3f); 
    view.setBackgroundDrawable(shape); 

我缺少什么?谢谢。

+1

你不能达到你的目标。看起来有一个公开的问题。检查这个答案:https://stackoverflow.com/a/14383974/334522 – sromku

+0

@sromku我看到这个帖子,但它是4岁,我想也许它已经解决了 – Phantom

+0

不幸的是,它不是,因为它从最后的评论从2017年起 - https://issuetracker.google.com/issues/36944181 :( – sromku

回答

1

您可以通过使用着色器

ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() { 
    @Override 
    public Shader resize(int width, int height) { 
     return new LinearGradient(width/2, 0, width/2, height, 
       new int[]{0xff000000, 0xff42f448, 0xff000000}, 
       new float[]{0, 0.3f, 1}, // start, center and end position 
       Shader.TileMode.CLAMP); 
    } 
}; 

PaintDrawable pd = new PaintDrawable(); 
pd.setShape(new RectShape()); 
pd.setShaderFactory(sf); 

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { 
    layout.setBackground(pd); 
} else 
    layout.setBackgroundDrawable(pd); 
+0

我试过你的解决方案,但结果是一样的,当我应用这种颜色时.setGradientCenter不做任何事情。 – Phantom

+0

@Phantom I编辑我的代码 – SiSa

+0

谢谢,这个解决方案有效。 – Phantom