Shouldn't the right be left + width for a view?

48 views Asked by At

For a custom view that draws a rectangle I see the following code in the onDraw

@Override
    protected void onDraw(Canvas canvas) {  
        int left = getPaddingLeft();
        int right = getWidth() - getPaddingLeft() - getPaddingRight();

        //etc
        canvas.drawRect(left, top, right, bottom, paint);
    } 

Shouldn't right be:

int right = left + getWidth() + getPaddingRight();  

i.e.

   int right =  getWidth() + left + getPaddingRight(); 

?

1

There are 1 answers

0
Pawel On BEST ANSWER

Right is essentially calculating width of the content so it's literally width without both paddings.

Excuse my crude ASCII explanation:

// horizontal views layout. It's total views width
// |--- left padding ---|--- content ---|--- right padding ---|

// |--- left padding ---|                    
int left = getPaddingLeft();

// |--- content ---|
int right = getWidth() - getPaddingLeft() - getPaddingRight();

// |--- left padding ---|--- content ---|--- right padding ---|
//                      ^_______________^
//                     left           right
canvas.drawRect(left, top, right, bottom, paint);

What you're suggesting:

int left = getPaddingLeft();

// |--- left padding ---|--- content ---|--- right padding ---|--- left padding ---|--- right padding ---|
int right =  getWidth() + left + getPaddingRight(); 

// |--- left padding ---|--- content ---|--- right padding ---|
//                      ^_____________________________________________________________________________________________________^
//                     left                                                       right
canvas.drawRect(left, top, right, bottom, paint);