1

I have a round corners layout, now I want to add a child view (an Imageview) which matches the parent layout's height and width.

My problem is that the child view hides the round corners of the parent.

enter image description here

How can I constrain it inside the borders of the parent layout without using the margin property, so that the parent's round corners stay visible?

PS: I created round corners of parent layout by overriding the onDraw() method.

My code:

protected void onDraw(Canvas canvas) {
    canvas.drawRect(0, 0, width, height, mpaint);
    super.onDraw(canvas);
}
Community
  • 1
  • 1
Newbie
  • 41
  • 3

3 Answers3

4

In my opinion, you can put your child views into a CardView(in support v7), which is actually a FrameLayout, but it handle the corners by just set one line of code:

app:cardCornerRadius="3dp"

It can clip the corner with the radius you set no matter what the child views are.

DysaniazzZ
  • 825
  • 15
  • 29
0

I suggest you add padding to the "rounded corner" view. This could be padding on all sides, bottom and top or left and right. Depending on what suits you the best.

I can't think of a more simple method than this. Your onDraw method looks fine, first the background than the child views.

Rolf ツ
  • 8,611
  • 6
  • 47
  • 72
0

When you add a child to your ViewGroup, that child is being drawn on top of your ViewGroup, thus your rounded corner doesn't take effect.

In order to achieve your goal you have to perform clipping on a certain path in your layout. That sounds a bit complicated, but in fact it is not.

Essentially, you can understand clipping as "cutting off" some part from your layout.

RectF rect = new RectF(0, 0, width, height);
path = new Path();
path.addRoundRect(rect, cornerRadius, cornerRadius, Direction.CW);

canvas.clipPath(path); // clipping here
// now anything that is outside this path will be "clipped", i.e. not drawn

You can refer to this for a complete source code.

Community
  • 1
  • 1
azizbekian
  • 60,783
  • 13
  • 169
  • 249