gpt4 book ai didi

objective-c - 将填充更改为已绘制的 NSBezierPath

转载 作者:行者123 更新时间:2023-12-03 17:29:23 27 4
gpt4 key购买 nike

我想更改我绘制的按钮的填充(我将 NSButton 子类化)

这是我已经得到的代码:

- (void)drawRect:(NSRect)dirtyRect {
// Drawing code here.
// Create the Gradient
NSGradient *fillGradient = [[NSGradient alloc] initWithStartingColor:[NSColor lightGrayColor] endingColor:[NSColor darkGrayColor]];
// Create the path
aPath = [NSBezierPath bezierPath];

[aPath moveToPoint:NSMakePoint(10.0, 0.0)];
[aPath lineToPoint:NSMakePoint(85.0, 0.0)];
[aPath lineToPoint:NSMakePoint(85.0, 20.0)];
[aPath lineToPoint:NSMakePoint(10.0, 20.0)];
[aPath lineToPoint:NSMakePoint(0.0, 10.0)];
[aPath lineToPoint:NSMakePoint(10.0, 0.0)];

[fillGradient drawInBezierPath:aPath angle:90.0];
[fillGradient release];
}

- (void)mouseDown:(NSEvent *)theEvent {
NSGradient *fillGradient = [[NSGradient alloc] initWithStartingColor:[NSColor lightGrayColor] endingColor:[NSColor darkGrayColor]];
[fillGradient drawInBezierPath:aPath angle:-90.0];
}

我收到一个 EXC_BAD_ACCESS 信号。我该怎么做?

最佳答案

EXC_BAD_ACCESS 的原因是以下行:

aPath = [NSBezierPath bezierPath];

创建一个autoreleased bezierPath,它将在运行循环的当前迭代结束时释放。为了避免该错误,您需要将其更改为:

aPath = [[NSBezierPath bezierPath] retain];

但是,您正在从错误的方向解决问题。绘图只能在 -drawRect: 方法(或仅从 -drawRect: 调用的方法)中完成。您应该为您的类创建一个新的 BOOL 实例变量(例如,称为 mouseIsDown )并在 mouseDown: 中进行设置。然后使用该 bool 值来确定如何填充按钮:

- (void)drawRect:(NSRect)aRect {
NSGradient *fillGradient = nil;
if (mouseIsDown)
fillGradient = [[NSGradient alloc] initWithStartingColor:[NSColor lightGrayColor] endingColor:[NSColor darkGrayColor]];
else
fillGradient = [[NSGradient alloc] initWithStartingColor:[NSColor lightGrayColor] endingColor:[NSColor darkGrayColor]];

// Do the rest of your drawRect method

}

- (void)mouseDown:(NSEvent *)theEvent {
mouseIsDown = YES;
[self setNeedsDisplay:YES];
}

- (void)mouseUp:(NSEvent *)theEvent {
mouseIsDown = NO;
[self setNeedsDisplay:YES];
}

关于objective-c - 将填充更改为已绘制的 NSBezierPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1926490/

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