How to draw semicircle on Android Canvas?

I just resolved a problem which at first I thought is a matter of 5 min for finding appropriate Android API function, unfortunately it took me much longer..

Problem:
Given start and end points of a vector, draw left/right hand semicircle knowing, that this vector is diameter of this semicircle.

Solution:

Use addArc android function.

public void addArc (RectF oval, float startAngle, float sweepAngle)
http://developer.android.com/reference/android/graphics/Path.html#addArc(android.graphics.RectF, float, float)

As you can see we need an oval rect and startAngle, which are not obvious..
Hereunder you can find a handy method computing needed parameters.

/**
     *
     * @param xStart vector start point
     * @param yStart
     * @param xEnd vector end point
     * @param yEnd
     * @param ovalRectOUT RectF to store result
     * @param enum direction left/right
     * @return start angle
     */
    public static float getSemicircle(float xStart, float yStart, float xEnd,
            float yEnd, RectF ovalRectOUT, Side direction) {

        float centerX = xStart + ((xEnd - xStart) / 2);
        float centerY = yStart + ((yEnd - yStart) / 2);

        double xLen = (xEnd - xStart);
        double yLen = (yEnd - yStart);
        float radius = (float) (Math.sqrt(xLen * xLen + yLen * yLen) / 2);
    
        RectF oval = new RectF((float) (centerX - radius),
                (float) (centerY - radius), (float) (centerX + radius),
                (float) (centerY + radius));

        ovalRectOUT.set(oval);

        double radStartAngle = 0;
        if (direction == Side.LEFT) {
            radStartAngle = Math.atan2(yStart - centerY, xStart - centerX);
        } else {
            radStartAngle = Math.atan2(yEnd - centerY, xEnd - centerX);
        }
        float startAngle = (float) Math.toDegrees(radStartAngle);

        return startAngle;

    }

After that drawing semicircles is deadsimple with eg.

path.addArc(oval, startAngle, 180);

Hope that helps! 😉

If you need to manipulate circle pieces a bit more specifically I really recommend you this article:
http://www.tbray.org/ongoing/When/200x/2009/01/02/Android-Draw-a-Curved-Line

One Comment

  • Thanks a lot. It’s Great!

Join the Discussion

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>