Android SweepGradient

BOE*_*GER 13 android gradient ondraw android-canvas

我有一个SweepGradient定义为

circle_paint.setShader(new SweepGradient(getWidth()/2, getHeight()/2, new int[] { circle_start_color, circle_end_color}, new float[] { 0f, 1f}))
Run Code Online (Sandbox Code Playgroud)

应用于定义为的拱门

canvas.drawArc(circle_bounds, circle_start_perc*360f, circle_end_perc*360f, true, circle_paint);
Run Code Online (Sandbox Code Playgroud)

这很好用,但我需要拱门从屏幕顶部开始绘图,即

canvas.drawArc(circle_bounds, ((circle_start_perc*360f)-90f)%360, circle_end_perc*360f, true, circle_paint);
Run Code Online (Sandbox Code Playgroud)

问题是SweepGradient似乎仍然从0度开始,我需要它从270度开始(类似于绘制弧线时的平移).换句话说,如果我有一个从白色到蓝色的渐变,我需要将弧的顶部涂成白色,并将弧的最后部分涂成蓝色.我怎样才能做到这一点?

Dev*_*red 18

你可以尝试使用getLocalMatrix(),并setLocalMatrix()SweepGradient一个旋转应用到着色器.您可以获取当前Matrix,发布适当的旋转,postRotate()然后将其设置回着色器元素.

另一种选择是旋转Canvas而不是.您可以预先旋转画布,绘制内容,然后将其恢复; 或先绘制内容,然后在事实后旋转画布.


Bre*_*ntM 17

使用以下方法旋转SweepGradient的原点Matrix.preRotate:

final int[] colors = {circle_start_color, circle_end_color};
final float[] positions = {0f, 1f};
Gradient gradient = new SweepGradient(circle_bounds.centerX(), circle_bounds.centerY(), colors, positions);
float rotate = 270f;
Matrix gradientMatrix = new Matrix();        
gradientMatrix.preRotate(rotate, circle_bounds.centerX(), circle_bounds.centerY());
gradient.setLocalMatrix(gradientMatrix);
mPaint.setShader(gradient);
Run Code Online (Sandbox Code Playgroud)