子类化 NSView 以具有透明背景

发布于 2024-10-11 04:43:47 字数 246 浏览 9 评论 0原文

我正在创建一个应用程序,我需要一个透明的 NSView,里面有一个透明的 PNG 图像。问题是,我正在绘制的 NSView 上有灰色背景。我将其子类化(作为透明矩形视图),但不知道在drawRect中放入什么以使其透明。

我已经重写了 isOpaque 方法以返回 NO 但它似乎没有帮助...

或者,是否已经有一个类似于 iPhone 的 UIImageView 的子类 NSView (只要我可以在里面添加子视图,我需要添加里面有一些文字)。

I am creating an app where I need to have a transparent NSView with a transparent PNG image inside. The problem is, the NSView I'm drawing has a gray background on it. I have it subclassed (as TransparentRectangleView) but don't know what to put in drawRect to make it transparent.

I have already overridden the isOpaque method to return NO but it doesn't seem to help...

Alternatively, is there already a subclassed NSView that is similar to the iPhone's UIImageView (as long as I can add subviews inside, I need to add some text inside).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

养猫人 2024-10-18 04:43:47

要使视图透明,只需用 [NSColor clearColor] 填充它即可。

- (void)drawRect:(NSRect)rect {
    [[NSColor clearColor] set];
    NSRectFill(rect);
}

isOpaque 的默认实现返回 NO,因此如果您子类化 NSView 而不是其他视图,则无需担心覆盖它。

To make a view transparent, simply fill it with [NSColor clearColor].

- (void)drawRect:(NSRect)rect {
    [[NSColor clearColor] set];
    NSRectFill(rect);
}

The default implementation of isOpaque returns NO, so if you are subclassing NSView and not some other view you don't need to worry about overriding it.

紫罗兰の梦幻 2024-10-18 04:43:47

接受的答案对我不起作用,因为我的窗口是不透明的。作为http://www.drissman.com/blog/archives/ 2009/10/09/nsrectfill_and_nscolor_clearcolor.html(以及下面的讨论)说,以下代码有效:

- (void)drawRect:(NSRect)rect {
    [[NSColor clearColor] set];
    NSRectFillUsingOperation(rect, NSCompositeSourceOver);
    // do other drawings
}

The accepted answer does not work for me since mine window is opaque. As http://www.drissman.com/blog/archives/2009/10/09/nsrectfill_and_nscolor_clearcolor.html (and the discussion below) said, the following codes work:

- (void)drawRect:(NSRect)rect {
    [[NSColor clearColor] set];
    NSRectFillUsingOperation(rect, NSCompositeSourceOver);
    // do other drawings
}
夜夜流光相皎洁 2024-10-18 04:43:47

斯威夫特版本:

override func draw(_ dirtyRect: NSRect) {

    NSColor.clear.set()
    dirtyRect.fill()
}

The Swift version:

override func draw(_ dirtyRect: NSRect) {

    NSColor.clear.set()
    dirtyRect.fill()
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文