gpt4 book ai didi

objective-c - 自定义圆形 NSSlider

转载 作者:行者123 更新时间:2023-12-03 17:42:37 24 4
gpt4 key购买 nike

我正在尝试实现一个自定义圆形 slider ,它使用图像来绘制表盘和旋钮。为此,我对 NSSliderCell 进行了子类化并覆盖 drawBarInsidedrawKnob方法。现在,如果我将 slider 类型保留为默认(水平),则会调用我的绘图函数并绘制图像,而不是默认的条和旋钮(当然,它看起来完全错误,因为图像是为圆形 slider 制作的,但它们是那里)。但是,一旦我将 slider 类型更改为圆形(在 IB 中或通过在 slider 单元格中设置 self.sliderType = NSCircularSlider;),这两种方法就永远不会被调用,并且我的图像不会被绘制(仅创建标准表盘)。我在这里忘记了什么吗?还是圆形 slider 根本无法自定义?

这是我的代码: DialSliderCellNSSliderCell 的子类并在名为 DialSlider 的类中启动并设置它是 NSSlider 的子类(这个类当时没有做任何其他事情)。

@implementation DialSliderCell

- (id)init {
self = [super init];
if (self) {
dialImage = [NSImage imageNamed:@"dial"];
knobImage = [NSImage imageNamed:@"dialKnob"];
self.sliderType = NSCircularSlider;
}
NSLog(@"init");
return self;
}

- (void)drawKnob:(NSRect)knobRect {
knobRect.size = knobImage.size;
[knobImage drawInRect:knobRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
NSLog(@"drawKnob");
}

- (void)drawBarInside:(NSRect)aRect flipped:(BOOL)flipped {
[dialImage drawInRect:aRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
NSLog(@"drawBarInside");
}

@end

最佳答案

我通过重写drawInteriorWithFrame方法解决了这个问题。解决方案是基于原来的方法。我只是删除了与圆形 slider 无关的任何内容,删除了原始图形并添加了我自己的图形。几何形状几乎完全是原创的。

- (void) drawInteriorWithFrame: (NSRect)cellFrame inView: (NSView*)controlView
{
cellFrame = [self drawingRectForBounds: cellFrame];
_trackRect = cellFrame;

NSPoint knobCenter;
NSPoint point;
float fraction, angle, radius;

knobCenter = NSMakePoint(NSMidX(cellFrame), NSMidY(cellFrame));

[dialImage drawInRect:cellFrame fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];

int knobDiameter = knobImage.size.width;
int knobRadius = knobDiameter / 2;
fraction = ([self floatValue] - [self minValue]) / ([self maxValue] - [self minValue]);
angle = (fraction * (2.0 * M_PI)) - (M_PI / 2.0);
radius = (cellFrame.size.height / 2) - knobDiameter;
point = NSMakePoint((radius * cos(angle)) + knobCenter.x,
(radius * sin(angle)) + knobCenter.y);

NSRect dotRect;
dotRect.origin.x = point.x - knobRadius;
dotRect.origin.y = point.y - knobRadius;
dotRect.size = knobImage.size;
[knobImage drawInRect:dotRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
}

cellFrame矩形的大小设置为dialImage图像的大小。

请注意,上面的方法似乎不会自动调用,因此我还必须重写 drawWithFrame 方法并使其调用 drawInteriorWithFrame:

- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
[self drawInteriorWithFrame:cellFrame inView:controlView];
}

关于objective-c - 自定义圆形 NSSlider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8723756/

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