Search code examples
androiddynamicandroid-asynctaskdrawshapes

Draw rectangle multiple times in new position not working


Each time I create a new rectangle with this code it does not work, I can only draw to a specified position, if I use a variable to change position on execution it does not draw anything.

Inside a Asynctask method:

rect = new desenho(main.this, x, y);
        

Which calls this:

public class desenho extends View{
    
    int x, y;
    Paint mPaint = new Paint();
    
    public desenho(Context context, int x, int y) {
        super(context);
        this.x = x;
        this.y = y;
        mPaint.setStrokeWidth(3);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(Color.BLACK);
    }
    
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(width, y);
    }
    
    @Override
    protected void onDraw(Canvas c) {
        // TODO Auto-generated method stub
        super.onDraw(c);
        c.drawRect(5, y, width-5, y+x, mPaint);
    }
}

Solution

  • It seems to me that you want the size to be independent of position. For that, these requirements must be met in your Canvas.drawRect(left, top, right, bottom, paint):

    • left - right = a
    • top - bottom = b

    where a, b are constant. Example:

    c.drawRect(xPos, yPos, xPos + width - 1, yPos + height - 1, mPaint);
    

    You see in this example that

    • left - right = xPos - (xPos + width - 1) = 1 - width
    • top - bottom = yPos - (yPos + height - 1) = 1 - height

    Both are constant → size is constant.