Saturday, 25 February 2017

How To Draw Circle In Android Canvas

    Create new Activity and remove R.layout.activity_main instead of set the our custom View class like DrawView into the setContentView() method and also pass the context of the activity into the DrawView constructor.
MainActivity.java

package com.androidsimplifycodes.canvas;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new DrawView(this));
    }
}
    Create a new class DrawView extends View. Override the onDraw(Canvas canvas) method to draw circle on Canvas. Take the Paint class object for the drawing to the surface of the canvas here use setAntiAlias() function i can talk later use of this function and setColor(int color) use for the set color of the circle or set color of the STROKE. setStrokeWidth(float width) use for the set boader width of the circle.
    If you want to make only bordered circle then use STROKE and if you want to use make fill circle then use FILL style according to the circle syntax into canvas first two parameter represent the center paint X and Y and third one indicate radius of the circle at last pass the your paint object into the canvas circle.
DrawView.java

package com.androidsimplifycodes.canvas;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

public class DrawView extends View {

    protected Paint paint;

    public DrawView(Context context) {
        super(context);
        initView();
    }

    private void initView() {
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(Color.GREEN);
        paint.setStrokeWidth(6f);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        paint.setStyle(Paint.Style.STROKE);
        canvas.drawCircle(getWidth() / 2, getHeight() / 4, 100, paint);

        paint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, 100, paint);
    }
}
Output :