Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a straight line in arc which connects the center with circumference

I have a custom view where I draw an arc. Now I also need to draw a line which joins the center and the circumference and should be exactly in the middle of arc.

Now I know that the code for drawing line in android canvas is fairly simple

but it does not involve angle and the arc is always using angle to draw itself.

So I can I draw the line in the same direction as the arc?

Am I clear here or do I need to explain more ?

Please help.

like image 967
Ankit Avatar asked Dec 21 '22 12:12

Ankit


1 Answers

Calculate the start point and the end point.

private class MView extends View {
    private Paint mPaint;
    private RectF mRect;
    private int mCenterX = 150;
    private int mCenterY = 150;

    public MView(Context context) {
        super(context);
        mPaint = new Paint();
        mPaint.setColor(Color.BLACK);
        mPaint.setStyle(Style.STROKE);
        mRect = new RectF(0, 0, mCenterX * 2, mCenterY * 2);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        float startAngle = 30;
        float sweepAngle = 60;

        canvas.drawArc(mRect, startAngle, sweepAngle, true, mPaint);
        float startX = mCenterX;
        float startY = mCenterY;
        float radius = mCenterX;
        float angle = (float) ((startAngle + sweepAngle / 2) * Math.PI / 180);
        float stopX = (float) (startX + radius * Math.cos(angle));
        float stopY = (float) (startY + radius * Math.sin(angle));

        canvas.drawLine(startX, startY, stopX, stopY, mPaint);
    }

}
like image 134
faylon Avatar answered Apr 29 '23 22:04

faylon