简体   繁体   English

子视图无法固定父形状

[英]child view not fix parent shape

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. 我有一个圆角布局,现在我想添加一个与父布局的高度和宽度相匹配的子视图(Imageview)。

My problem is that the child view hides the round corners of the parent. 我的问题是子视图隐藏了父视图的圆角。

在此处输入图片说明

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? 我如何在不使用margin属性的情况下将其限制在父布局的边界内,以使父级的圆角保持可见?

PS: I created round corners of parent layout by overriding the onDraw() method. PS:我通过覆盖onDraw()方法创建了父布局的圆角。

My code: 我的代码:

protected void onDraw(Canvas canvas) {
    canvas.drawRect(0, 0, width, height, mpaint);
    super.onDraw(canvas);
}

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: 我认为,您可以将您的子视图放入CardView (支持v7),该视图实际上是FrameLayout ,但是只需设置一行代码即可处理角落:

app:cardCornerRadius="3dp"

It can clip the corner with the radius you set no matter what the child views are. 无论子视图是什么,它都可以使用您设置的半径来夹角。

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. 您的onDraw方法看起来不错,首先是背景而不是子视图。

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. 将子级添加到ViewGroup ,该子级将绘制在ViewGroup顶部,因此圆角不会生效。

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. 您可以参考以获取完整的源代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM