我想用 bottom - >创建一个带渐变的CircleView。左 - >顶部 - >右即可。
所以我使用像这样的SweepGradient
画布
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);
}
但默认顺序是右 - >底部 - >左 - >顶部但我想底部 - >左 - >顶部 - >右 我已经尝试将职位改为
float[] positions = {0.25f, 1.25f};
但它仅适用于AndroidStudio的Preview
,当我在真实设备中运行时,它会显示与positions = {0, 1}
如何从SweepGradient
这样的<{p}}制作bottom -> left -> top -> right
渐变
---更新---
我们可以setLocalMatrix
使用SweepGradient
这样来旋转渐变
Matrix matrix = new Matrix();
matrix.setRotate(90, 100, 100);
gradient.setLocalMatrix(matrix);
答案 0 :(得分:5)
在绘制圆圈之前旋转画布。
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);
}