Android SweepGradient

时间:2012-11-15 18:15:47

标签: android android-canvas ondraw gradients

我将SweepGradient定义为

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

应用于定义为

的拱门
canvas.drawArc(circle_bounds, circle_start_perc*360f, circle_end_perc*360f, true, circle_paint);

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

canvas.drawArc(circle_bounds, ((circle_start_perc*360f)-90f)%360, circle_end_perc*360f, true, circle_paint);

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

2 个答案:

答案 0 :(得分:18)

您可以尝试使用getLocalMatrix()上的setLocalMatrix()SweepGradient将旋转应用于着色器。您可以获取当前Matrix,使用postRotate()发布相应的旋转,然后将其设置回着色器元素。

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

答案 1 :(得分:16)

使用Matrix.preRotate

旋转SweepGradient的原点
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);