Sunday, 26 February 2017

How To Draw Rectangle 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 rectangle on Canvas. Take the Paint class object for the drawing to the surface of the canvas here use setAntiAlias() function discuss later use of this function and setColor(int color) use for the set color of the rectangle or set color of the STROKE. setStrokeWidth(float width) use for the set boader width of the rectangle.
    If you want to make only bordered rectangle then use STROKE and if you want to use make fill rectangle then use FILL style according to the rectangle syntax we can draw rectangle using three type of methods.

public void drawRect(float left, float top, float right, float bottom, Paint paint);
 Passing float parameter into this function and at last passing the paint object for the drawing.

public void drawRect(Rect r, Paint paint);
 here, use Rect class is container for the store the integer parameter of the left, top, right, bottom of the rectangle.

public void drawRect(RectF rect, Paint paint);
 here, use RectF class is same as above class but store the float parameter of the left, top, right, bottom of the rectangle.
DrawView.java

package com.androidsimplifycodes.canvas;

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

public class DrawView extends View {

    protected Paint paint;
    protected Rect rect;
    protected RectF rectF;

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

    private void initView() {
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(6f);

        rect = new Rect(125, 125, 525, 525);
        rectF = new RectF(150.25f, 150.25f, 550.25f, 550.25f);
    }

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

        paint.setColor(Color.RED);
        canvas.drawRect(100f, 100f, 500f, 500f, paint);

        paint.setColor(Color.GREEN);
        canvas.drawRect(rect, paint);

        paint.setColor(Color.BLUE);
        canvas.drawRect(rectF, paint);
    }
}
Output :