[英]Custom circular NSSlider
我正在嘗試實現一個自定義的圓形滑塊,它使用圖像來繪制表盤和旋鈕。 為此,我已經子類化了NSSliderCell
並覆蓋了drawBarInside
和drawKnob
方法。 現在,如果我將滑塊類型保留為默認(水平),則會調用我的繪圖函數並繪制圖像而不是默認的條形和旋鈕(當然,由於圖像是針對圓形滑塊制作的,因此它看起來完全錯誤,但它們是那里)。 但是一旦我將滑塊類型更改為圓形(在IB中或通過設置self.sliderType = NSCircularSlider;
在我的滑塊單元格中),這兩種方法永遠不會被調用,我的圖像也不會被繪制(只創建標准刻度盤)。 我忘了這里的東西,還是圓形滑塊根本不能定制?
這里是我的代碼: DialSliderCell
是的子類NSSliderCell
,並開始在一個名為類中設置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
方法解決了這個問題。 解決方案基於原始方法。 我剛刪除了與圓形滑塊無關的任何內容,刪除了原始圖形並添加了我自己的圖形。 幾何幾乎完全是原始的。
- (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];
}
我能想到的是,你並沒有壓倒所有指定的初始化者
來自文檔......
指定的初始化程序。 子類化NSCell時,必須實現所有指定的初始值設定項。 那些方法是:init,initWithCoder:,initTextCell:和initImageCell:。
可能是其他3個中的一個被稱為圓形滑塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.