1

I've drawn a square but how can I place another one beside it without any gaps? I believe the first parameter (0) in mRedRect1F needs to change but I don't know what to.

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    mRedRect0F = new RectF(0, 0, 50, 50);
    mRedRect1F = new RectF(0, 0, 50, 50);

    canvas.drawRect(mRedRect0F, mRedRectPaint);
    canvas.drawRect(mRedRect1F, mRedRectPaint);

}

Update

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    mRedRect0F = new RectF(0, 0, 20, measuredHeight);
    mRedRect1F = new RectF(getWidth() - 20, 0, getWidth(), getHeight());

    canvas.drawRect(mRedRect0F, mRedRectPaint);
    canvas.drawRect(mRedRect1F, mRedRectPaint);
}
wbk727
  • 8,017
  • 12
  • 61
  • 125

2 Answers2

1

There are 3 ways you could accomplish this off the top of my head.

The first is to define the second RecfF as 50 pixels further to the right.

new RectF(50, 0, 100, 50);

The next is to translate the canvas before drawing the second.

mRedRect = new RectF(0, 0, 50, 50);
canvas.drawRect(mRedRect, mRedRectPaint);
canvas.translate(50, 0);
canvas.drawRect(mRedRect, mRedRectPaint);

And the 3rd is to offset the RectF before drawing.

mRedRect = new RectF(0, 0, 50, 50);
canvas.drawRect(mRedRect, mRedRectPaint);
mRedRect.offset(50, 0);
canvas.drawRect(mRedRect, mRedRectPaint);
alex
  • 6,359
  • 1
  • 23
  • 21
  • I don't want to use numbers. Is it possible to have something like `android:layout_toRightOf(mRedRect0F)`? – wbk727 May 13 '15 at 00:04
  • Not really, if you want to use a layout, use a layout. – alex May 13 '15 at 00:08
  • Do you know a proper solution for solving [this other issue programmatically (in Java using canvas not XML)](http://stackoverflow.com/questions/32037260/how-to-add-rectangles-on-top-of-existing-rectangle-in-canvas)? I've spent months trying to solve this issue but have had no luck and the answers that have been given don't solve the problem either. – wbk727 Aug 19 '15 at 19:05
1

You could create a toRightOf method. Sure it would be more work, but if you ever needed to do this sort of thing again you'd already have the method written to do it. I'm not at a computer at the moment or I would give it a try. If you don't expect to do this more than once I would use one of the options posted in the first answer.