gpt4 book ai didi

android - 动态改变渐变中心

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:40:57 24 4
gpt4 key购买 nike

我有以下渐变

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

我错过了什么?谢谢。

最佳答案

你可以通过Shader实现你的目标

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

关于android - 动态改变渐变中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46682667/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com