NSView 上的圆角矩形会剪辑所有包含子视图
我正在创建一个具有圆角的 NSView 子类。该视图旨在成为一个容器,其他子视图将添加到其中。我试图获取 NSView 的圆角来剪辑所有子视图的角,但无法获取它。
- (void)drawRect:(NSRect)dirtyRect {
NSRect rect = [self bounds];
NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:self.radius yRadius:self.radius];
[path addClip];
[[NSColor redColor] set];
NSRectFill(dirtyRect);
[super drawRect:dirtyRect];
}
红色只是举例。如果我向矩形添加子视图,则不会剪切角:
如何实现此目的?
I am creating a NSView
subclass that has rounded corners. This view is meant to be a container and other subviews will be added to it. I am trying to get the rounded corners of the NSView
to clip all of the subview's corners as well, but am not able to get it.
- (void)drawRect:(NSRect)dirtyRect {
NSRect rect = [self bounds];
NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:self.radius yRadius:self.radius];
[path addClip];
[[NSColor redColor] set];
NSRectFill(dirtyRect);
[super drawRect:dirtyRect];
}
The red is just for example. If I add a subview to the rect, The corners are not clipped:
How can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用核心动画图层将正确剪辑子图层。
在你的容器 NSView 子类中:
Using Core Animation layers will clip sublayers correctly.
In your container NSView subclass:
您可以在界面构建器中执行此操作无需子类化添加用户定义的运行时属性”
You can do it in the interface builder without subclassing adding User Defined Runtime Attributes"
你尝试过用图层进行裁剪吗?self.layer.cornerRadius = self.radius;
self.layer.masksToBounds = YES;
啊,抱歉,不知何故我错过了你在谈论 NSView,而不是 UIView。在所有情况下都很难剪切 NSView 子视图,因为似乎大多数 Cocoa 标准视图都设置了自己的剪切路径。使用一些填充来布局子视图可能会更容易,并且避免了剪裁的需要。
Have you tried clipping with layers?self.layer.cornerRadius = self.radius;
self.layer.masksToBounds = YES;
Ah, sorry, somehow I've missed that you were talking about NSView, not UIView. It would be hard to clip NSView subviews in all cases because it seems that most of Cocoa standard views set their own clipping path. It might be easier to layout subviews with some paddings and avoid need for clipping.