Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing a rectangle in center of the screen

Tags:

android

please see the following code. I want draw a rectangle in center of the screen.But it draws a rectangle in the left corner.

protected  void onDraw(Canvas canvas) {
        paint.setColor(Color.GREEN);
        canvas.drawRect(getLeft()/2,getTop()/2,getRight()/2,getBottom()/2,paint);
        super.onDraw(canvas);
    }
like image 879
developer Avatar asked Jul 08 '15 13:07

developer


1 Answers

Something like that?

    protected void onDraw(Canvas canvas) {
        int canvasW = getWidth();
        int canvasH = getHeight();
        Point centerOfCanvas = new Point(canvasW / 2, canvasH / 2);
        int rectW = 100;
        int rectH = 100;
        int left = centerOfCanvas.x - (rectW / 2);
        int top = centerOfCanvas.y - (rectH / 2);
        int right = centerOfCanvas.x + (rectW / 2);
        int bottom = centerOfCanvas.y + (rectH / 2);
        Rect rect = new Rect(left, top, right, bottom);
        canvas.drawRect(rect, new Paint());
    }
like image 153
Tronum Avatar answered Oct 26 '22 03:10

Tronum