How to draw a rectangle in Android (using onDraw method of View)

Android FAQ: How do I draw a rectangle in Android?

To draw a rectangle in Android you’ll need to create your own View, i.e., a class that extends the Android View class. For example, this CustomView shows how to extend a View and then use the Rect and Paint classes along with the onDraw method to draw a rectangle:

package com.alvinalexander.rectangledemo;

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

public class CustomView extends View {
    
    private Rect rectangle;
    private Paint paint;

    public CustomView(Context context) {
        super(context);
        int x = 50;
        int y = 50;
        int sideLength = 200;
        
        // create a rectangle that we'll draw later
        rectangle = new Rect(x, y, sideLength, sideLength);

        // create the Paint and set its color        
        paint = new Paint();
        paint.setColor(Color.GRAY);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(Color.BLUE);
        canvas.drawRect(rectangle, paint);
    }

}

Now all you have to do is use this CustomView in your Activity:

package com.alvinalexander.rectangledemo;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new CustomView(this));
    }

}

If you set this as the main Activity of your Android application and then run it in an emulator, it should look like this:

In summary, if you wanted to see how to draw a rectangle in Android, I hope this is helpful.

Comments

Permalink

After searching for about 30 minutes on the web for a useful piece of example code, YOURS was the most helpful and actually exactly what i needed. thank you.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.