如何使用非透明窗口创建内部透明nsview

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用非透明窗口创建内部透明nsview相关的知识,希望对你有一定的参考价值。

我试图在非透明窗口中创建不透明边框。目前我寻找子视图并创建bezierpath来填充外部区域。还有其他方法怎么做?

示例我想要实现的目标:

enter image description here

#import "MyView2.h"
#import "MyView.h"

@interface MyView2() {
    NSRect transparentSubviewRect;
}

@end

@implementation MyView2

- (void)awakeFromNib
{
    NSArray *subviews = [self subviews];
    for (NSView *view in subviews) {
        if ([view isKindOfClass:[MyView class]]) {
            transparentSubviewRect = [view frame];
        }
    }
}

- (void)drawRect:(NSRect)dirtyRect {
    NSRect rect = [self frame];
    NSBezierPath *path = [NSBezierPath bezierPath];
    [path moveToPoint:NSMakePoint(NSMaxX(transparentSubviewRect), NSMaxY(transparentSubviewRect))];
    [path lineToPoint:NSMakePoint(NSMinX(transparentSubviewRect), NSMaxY(transparentSubviewRect))];
    [path lineToPoint:NSMakePoint(NSMinX(transparentSubviewRect), NSMinY(transparentSubviewRect))];
    [path lineToPoint:NSMakePoint(NSMaxX(transparentSubviewRect), NSMinY(transparentSubviewRect))];
    [path lineToPoint:NSMakePoint(NSMaxX(transparentSubviewRect), NSMaxY(transparentSubviewRect))];
    [path closePath];
    [path moveToPoint:NSMakePoint(NSMaxX(rect), NSMaxY(rect))];
    [path curveToPoint: NSMakePoint(NSMaxX(rect), NSMinY(rect))
               controlPoint1: NSMakePoint(NSMaxX(transparentSubviewRect), NSMaxY(transparentSubviewRect))
               controlPoint2: NSMakePoint(NSMaxX(rect), NSMinY(transparentSubviewRect))];
    [path lineToPoint:NSMakePoint(NSMinX(rect), NSMinY(rect))];
    [path lineToPoint:NSMakePoint(NSMinX(rect), NSMaxY(rect))];
    [path lineToPoint:NSMakePoint(NSMaxX(rect), NSMaxY(rect))];
    [path lineToPoint:NSMakePoint(NSMaxX(rect), NSMaxY(rect))];
    [path closePath];
    [[NSColor windowBackgroundColor] setFill];
    [path fill];
}

@end

#import "MyWindow.h"

@implementation MyWindow


- (BOOL)isOpaque
{
    return NO;
}

- (NSColor *)backgroundColor
{
    return [NSColor colorWithCalibratedWhite:0.0 alpha:0.3];
}

@end
答案

更简单的解决方案是填充整个视图并使用NSCompositingOperationClear操作。必须是不透明窗口+窗口的一些透明背景颜色。

- (void)drawRect:(NSRect)dirtyRect {
    [[NSColor windowBackgroundColor] setFill];
    NSRectFill([self bounds]);
    NSRectFillUsingOperation(transparentSubviewRect, NSCompositingOperationClear);
}

以上是关于如何使用非透明窗口创建内部透明nsview的主要内容,如果未能解决你的问题,请参考以下文章

如何使 NSView 透明,但保留属于它的对象? [复制]

事件在透明 NSWindow 中的 NSView 中不起作用

如何使用 Win32 API 阻止来自透明窗口的鼠标输入?

在透明父元素之上创建非透明 div

如何在非透明背景上创建透明文本

如何使用 GD 或 Imagick 在非透明纯色图像内创建透明区域?