gpt4 book ai didi

cocoa - NSView 上的圆角矩形会剪辑所有包含 subview

转载 作者:行者123 更新时间:2023-12-03 16:02:09 24 4
gpt4 key购买 nike

我正在创建一个具有圆角的 NSView 子类。该 View 旨在成为一个容器,其他 subview 将添加到其中。我试图获取 NSView 的圆角来剪辑所有 subview 的角,但无法获取它。

- (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];
}

红色只是举例。如果我向矩形添加 subview ,则不会剪切角: enter image description here

我怎样才能实现这个目标?

最佳答案

使用核心动画图层将正确剪辑子图层。

在你的容器 NSView 子类中:

- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.layer = _layer; // strangely necessary
self.wantsLayer = YES;
self.layer.masksToBounds = YES;
self.layer.cornerRadius = 10.0;
}
return self;
}

关于cocoa - NSView 上的圆角矩形会剪辑所有包含 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5087542/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com