Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android SweepGradient

I have a SweepGradient defined as

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

applied to a arch defined as

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

This workes well, but I need the arch to start drawing from the top of the screen, i.e.

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

The problem is that the SweepGradient seems to still start at 0 degrees, and i need it to start at 270 degrees (similar to the translation done on the drawing of the arc). In other words if I have a gradient from white to blue, I need the top of the arc painted white en the last part of the arc painted blue. How can I do this?

like image 610
BOENDAGGER Avatar asked Nov 15 '12 18:11

BOENDAGGER


2 Answers

Rotating the origin of the SweepGradient using a 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);
like image 61
BrentM Avatar answered Nov 19 '22 23:11

BrentM


You might try using getLocalMatrix() and setLocalMatrix() on the SweepGradient to apply a rotation to the shader. You can get the current Matrix, post the appropriate rotation with postRotate() and then set it back to the shader element.

Another option would be to rotate the Canvas instead. You could pre-rotate the Canvas, draw the content, and then restore it; or draw the content first and then rotate the canvas after the fact.

like image 20
devunwired Avatar answered Nov 20 '22 01:11

devunwired