gpt4 book ai didi

android - SweepGradient 改变开始和结束颜色的位置

转载 作者:太空狗 更新时间:2023-10-29 16:30:22 33 4
gpt4 key购买 nike

我想创建一个从底部 -> 左侧 -> 顶部 -> 右侧 渐变的 CircleView。
所以我像这样使用带有 SweepGradient 的 Canvas

protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();

int[] colors = {Color.GREEN, Color.RED};
float[] positions = {0, 1};

SweepGradient gradient = new SweepGradient(100, 100, colors, positions);
paint.setShader(gradient);
canvas.drawCircle(100, 100, 100, paint);
}

enter image description here

但默认顺序是 right -> bottom -> left -> top 但我想要 bottom -> left -> top -> right我试过将位置更改为

float[] positions = {0.25f, 1.25f};

但它只适用于 AndroidStudio 的 Preview,当我在真实设备上运行时,它显示的结果与 positions = {0, 1} 相同

如何从 bottom -> left -> top -> right 像这样制作 SweepGradient 渐变

enter image description here

---更新---我们可以为 SweepGradient 使用 setLocalMatrix 像这样旋转渐变

Matrix matrix = new Matrix();
matrix.setRotate(90, 100, 100);
gradient.setLocalMatrix(matrix);

enter image description here

最佳答案

画圆之前旋转 Canvas 。

public class CircleView extends View {
private Paint paint;

public CircleView(Context context) {
super(context);
init();
}

public CircleView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}

public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}

public void init() {
paint = new Paint();

int[] colors = {Color.GREEN, Color.RED};
float[] positions = {0, 1};
SweepGradient gradient = new SweepGradient(100, 100, colors, positions);
paint.setShader(gradient);
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
canvas.rotate(90, 100, 100);
canvas.drawCircle(100, 100, 100, paint);
canvas.restore();
}
}

编辑-1:
@pkskink 建议的替代方法就是用setLocalMatrix如下所示:

public void init() {      
int[] colors = {Color.GREEN, Color.RED};
float[] positions = {0, 1};

Matrix matrix = new Matrix();
matrix.postRotate(90, 100, 100);

Shader gradient = new SweepGradient(100, 100, colors, positions);
gradient.setLocalMatrix(matrix);

paint = new Paint();
paint.setShader(gradient);
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(100, 100, 100, paint);
}

关于android - SweepGradient 改变开始和结束颜色的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40828108/

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