代码之家  ›  专栏  ›  技术社区  ›  Phantom

动态更改渐变中心

  •  5
  • Phantom  · 技术社区  · 7 年前

    我有以下梯度

    <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 回复  |  直到 7 年前
        1
  •  4
  •   SiSa    7 年前

    使用着色器可以实现目标

    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);