Objective c 鼠标插入事件上的NSButton图像阴影

Objective c 鼠标插入事件上的NSButton图像阴影,objective-c,cocoa,mouseevent,nsbutton,nsevent,Objective C,Cocoa,Mouseevent,Nsbutton,Nsevent,我有一个无边界的NSButton,它包含一个图像,并且是ButtonEffect类的子类,用于检测mouseEntered和mouseExited事件。我的目标是当鼠标进入按钮区域时,使图像的边缘发光。我知道我可以通过使用两个不同的图像(一个有阴影,另一个没有阴影)来实现这一点,但我需要使用一个图像 下面是一个我希望为mouseEntered活动实现的示例: 以下是光标离开按钮区域后应注意的事项: 我尝试设置单元格的背景,但它会改变整个按钮区域的颜色 #import "ButtonEffec

我有一个无边界的NSButton,它包含一个图像,并且是ButtonEffect类的子类,用于检测mouseEntered和mouseExited事件。我的目标是当鼠标进入按钮区域时,使图像的边缘发光。我知道我可以通过使用两个不同的图像(一个有阴影,另一个没有阴影)来实现这一点,但我需要使用一个图像

下面是一个我希望为mouseEntered活动实现的示例:

以下是光标离开按钮区域后应注意的事项:

我尝试设置单元格的背景,但它会改变整个按钮区域的颜色

#import "ButtonEffect.h"

@interface ButtonEffect ()

@property NSTrackingArea *trackingArea;

@end

@implementation ButtonEffect

- (void)updateTrackingAreas {
    [super updateTrackingAreas];

    if (_trackingArea) {
        [self removeTrackingArea:_trackingArea];
    }

    NSTrackingAreaOptions options = NSTrackingInVisibleRect | NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow;
    _trackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect options:options owner:self userInfo:nil];
    [self addTrackingArea:_trackingArea];
}

- (void)mouseEntered:(NSEvent *)event {
    [[NSCursor pointingHandCursor] set];
    [self.cell setBackgroundColor:NSColor.redColor];
    NSLog(@"mouse entered button");
}

- (void)mouseExited:(NSEvent *)event {
    [[NSCursor arrowCursor] set];
    [self.cell setBackgroundColor:nil];
    NSLog(@"mouse exited button");
}

@end

你想要这样的吗

     - (void)mouseEntered:(NSEvent *)event {
    CALayer *lay=[btn layer];
    CGColorRef myColor=CGColorCreateGenericRGB(1, 1, 1, 1);
    CGColorRelease(myColor);
    myColor=CGColorCreateGenericRGB(0, 0, 0.8, 1);
    [lay setBorderColor:myColor];
    [lay setBorderWidth:1];
    [btn setWantsLayer:YES];
    [btn setLayer:lay];
    CGColorRelease(myColor);

}

- (void)mouseExited:(NSEvent *)event {
    CALayer *lay=[btn layer];
    CGColorRef myColor=CGColorCreateGenericRGB(1, 1, 1, 1);
    CGColorRelease(myColor);
    myColor=CGColorCreateGenericRGB(0, 0, 0.8, 1);
    [lay setBorderColor:myColor];
    [lay setBorderWidth:0];
    [btn setWantsLayer:YES];
    [btn setLayer:lay];
    CGColorRelease(myColor);

}

@Suresh是的,我知道我可以使用两个不同的图像来实现这一点,但我的目标是只使用一个图像。@Gavin我已经更新了我的答案。我使用了CALayer的辉光效果(不完全是)。您可以做一些修改。@Suresh您也可以使用NSShadow来完成效果