Ad

How Can I Draw More Rectangles In A Raw On A Canvas?

- 1 answer

I was doing an test app for developing in the future a more complex one, and I'm asking myself if I can draw more rectangles on a canvas (maybe one left, one center and one right). Without using any ImageView, TextView or this things. Here's my code:

public class MioCanvas extends View {

Paint paint;
Rect rect;

public MioCanvas(Context context) {
    super(context);
    paint = new Paint();
    rect = new Rect();
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    paint.setColor(Color.GRAY);
    paint.setStrokeWidth(3);
    canvas.drawRect(0, 1999999, canvas.getWidth() / 2, canvas.getHeight() / 2, paint);
}
}

And here's the activity:

public class MainActivity extends AppCompatActivity {

MioCanvas mioCanvas;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mioCanvas = new MioCanvas(this);
    mioCanvas.setBackgroundColor(Color.GREEN);
    setContentView(mioCanvas);
}
}
Ad

Answer

To achieve what you want you can, for example, create an Object called MyRectangle, and in it you will keep reference to its width, height, positionX, positionY, color reference, etc.

Inside your MioCanvas class put a global variable such as:

List<MyRectangle> rectangleList;

Initialise it in your constructor, create a few rectangles and add them to the list.

Lastly iterate through the list inside onDraw method as such to draw the rectangles:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    for(MyRectangle rectangle : rectangleList){
        paint.setColor(rectangle.getColour());
        paint.setStrokeWidth(rectangle.getStroke());
        canvas.drawRect(rectangle.getPositionX(), rectangle.getPositionY(), rectangle.getWidth() / 2, rectangle.getHeight() / 2, paint);
    }
}
Ad
source: stackoverflow.com
Ad