Search code examples
androidcanvasandroid-canvas

Spaces between arcs in canvas


The goal is to draw a circle having arcs that representing time slices. I have done this:

enter image description here

The problem is that there is a white space between each arch and I want to remove it. Also, the arcs are not aligned. This is my code:

    int x = getWidth()/2;
    int y = getHeight()/2;
    int stroke = 20;
    int radiusExternal = 250;

    final RectF rect2 = new RectF();
    rect2.set(x - radiusExternal, y - radiusExternal, x + radiusExternal, y + radiusExternal);
    for (int i = 0; i < modProgram.getListEvents().size(); i++) {
        ModEvent event = modProgram.getListEvents().get(i);
        Paint paint2 = new Paint();

        paint2.setColor(getColorEvent(event));
        paint2.setStrokeWidth(stroke);
        paint2.setAntiAlias(true);
        paint2.setStrokeCap(Paint.Cap.BUTT);
        paint2.setStyle(Paint.Style.STROKE);
        int initialAngle = getInitialAngle(modProgram, event.getStartEvent());
        int sweepAngle = getSweepAngle(modProgram, event, initialAngle);
        canvas.drawArc(rect2, initialAngle, sweepAngle, false, paint2);
    }

Solution

  • This is probably only a partial answer to deal with the gap between the arc-segments.

    Here's a fiddle with javascript: http://jsfiddle.net/oakvLadb/

    I've just randomly generated some start- and stop-angles.

    The important part lies in the drawing of the arc:

    ctx.arc(c.width/2,c.height/2,radius,startAngle,stopAngle+anglePadding);
    

    The anglePadding is there to make sure that a little extra is drawn. When the next segment starts off being drawn from the previous segment's stopAngle, there will be a slit overlapp, making sure no gap is visible.

    Next for the poor fit of the arc-segments

    When it comes to the fact that it seems like the segments aren't meeting up correctly, the only thing I can think of is that the segments that you're drawing are not those of a perfect circle but an oval, and that's why they're not meeting up correctly. If your rect2 variable doesn't hold data for a perfect square, your segments won't match.

    It looks like you do have a perfect square so they should align. Somewhere, there's a rounding error of some kind...