Search code examples
androidcanvasandroid-viewandroid-custom-view

How canvas.drawRect draws a rectangle


I have to create a custom view where I have to draw a rectangle. I'm trying to use the canvas.drawRect method. I wanted to create rectangles somethig like this enter image description here

the gray colored one is my custom view which is extending the View class. Inside the onDraw method I'm trying to draw the rectangle.

But actually I'm confused with the parameters of the drawRect method.

As per the documentation

/**
 * Draw the specified Rect using the specified paint. The rectangle will
 * be filled or framed based on the Style in the paint.
 *
 * @param left   The left side of the rectangle to be drawn
 * @param top    The top side of the rectangle to be drawn
 * @param right  The right side of the rectangle to be drawn
 * @param bottom The bottom side of the rectangle to be drawn
 * @param paint  The paint used to draw the rect
 */

What I assume is that left and top forms the x,y coordinates of the starting point, and right is the width and bottom is the height. But it doesn't seem to work that way.

I tried something like this to draw one rectangle but it does not draw anything

       paint.setColor(Color.BLUE);
       canvas.drawRect(5, canvas.getHeight()/2, 30, 30, paint );

Can anyone please tell how exactly a rectangle is drawn using these values?

It would be very helpful if someone could show the code to draw at least the first rectangle.

My requirement is like, the number of inner rectangles are dynamic, so if I pass some 4 to this View, it should create 4 equal width rectangles horizontally. something like enter image description here

Thanks in advance!!


Solution

  • But actually I'm confused with the parameters of the drawRect method.

    The drawRect method requires only two coordinates to draw a rectangle. The top left corner and the bottom right corner. So the 4 points form these 2 coordinates in your canvas. Hope it is clear from the below images

    enter image description here

    P1 and P2 are points formed by (left,top) and (right,bottom), So the drawn rectangle would be like this.

    enter image description here

    To draw rectangles dynamically like you have shown in you image , try something like this

    int[] colors = new int[]{Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW}; // given some fixed colors
    

    in you onDraw method

    @Override
    protected void onDraw(Canvas canvas) {
    int padding = 5;
    float rectangleWidth = (getMeasuredWidth() - padding * 2) / colors.length;
    for (int i = 0; i < colors.length; i++) {
        paint.setColor(colors[i]);
        canvas.drawRect(padding + (rectangleWidth * i),
                        getMeasuredHeight() / 2,
                        padding + rectangleWidth * (i + 1),
                        getMeasuredHeight() - padding, paint
        ); // 5 px is the padding given to the canvas
    }
    

    }