Friday, March 18, 2016

ClipRect: Draw outside of the box

Do you know how to draw something like this in Android?

Yes, canvas.drawRoundRect()!

radius = height / 2;
rect.set(0, 0, width, height);
canvas.drawRoundRect(rect, radius, radius, paint);

How about something like this?

It kind of looks like the rectangle with rounded corners. If only there is a way to chop off the end! Well, there is: clipRect.

When you clip a canvas, you are telling Android to draw only inside that rectangle. This allows us to color outside of the box, so to speak, but only keep the part that is inside the box. In our case, we will draw a round rect with size width + height by height, but clip it to width by height so the rounded part on the right is "outside".

canvas.save();
canvas.clipRect(0, 0, width, height);

rect.set(0, 0, width + height, height);
canvas.drawRoundRect(rect, radius, radius, paint);

canvas.restore();

Remember to save and restore so the rest of your app can draw wherever it wants.

Challenge

The source code is in ClipRectActivity in android-graphics-demo.

Can you modify it to clip the rectangle on the other side?

Bonus: Try these other techniques!

1 comment:

Inline coding questions will not be answsered. Instead, ask on StackOverflow and put the link in the comment.

  1. The beauty of the internet and smart twitter friends: you come with a nice solution, smart people come with nice alternatives. TIL three ways to draw a chopped rounded corner rectangle.

    ReplyDelete