Question

I am trying to modify a joystick component for the android device. Currently the component is able to track the x and y position of your finger and draw a small circle there. Now what I want to do is draw a rectangle or arc from the center to the x and y position of your finger.

As far as I know the rectangle only takes top, left, right and bottom values which only allows me to draw rectangles either horizontal or vertically. If someone knows another way to draw this that would be fantastic.

I have managed to get a straight rectangle using canvas.drawLine however I now want to make the rectangle curved using the drawArc function, this however takes an argument of RectF.

My code that I am currently using is:

@Override
protected void onDraw(Canvas canvas) {

    int centerX = (getWidth())/2;
    int centerY = (getHeight())/2;
    Paint p = new Paint();
    p.setColor(buttonColor);

    RadialGradient gradient = new RadialGradient( centerX, centerY, joystickRadius,
    backgroundColor,circleColor, android.graphics.Shader.TileMode.CLAMP);

    //draw an outer circle
    p.setDither(true);
    p.setShader(gradient);
    canvas.drawCircle( (int) centerX, (int) centerY, joystickRadius, p);


    p.setShader(null);
    p.setColor(buttonColor);
    p.setStyle(Paint.Style.FILL);

    //draw the joystick thumbpad
    canvas.drawCircle(x, y, buttonRadius, p);

    // draw a line from the centre of outer circle to the center of the 
    // thumbpad. I want this to be a curved rectangle instead.
    canvas.drawLine( centerX, centerY, x, y, p);
}
Was it helpful?

Solution

I assume that you are trying to draw a rectangle from the centre to the contact point?

Take a look at Canvas.save/restore. Some pseudo code:

canvas.save()

canvas.rotate(angleOfRectangle)

canvas.drawRectangle(size)

canvas.restore()

The idea is to save the current canvas state, rotate the entire canvas, draw your rectangle then restore the canvas state to "forget" about the rotation".

[EDIT]

Thanks for Matt for the correction.

Hope it helps...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top