月別アーカイブ: 2008年8月

ジョグホイール

iPodのクリックホイールのように、グルグルと円を描いて値を増減させる例です。NSViewのサブクラスで以下のような感じに。1周まわすと1.0増減します。

//
// YKJogWheelView.h
//

#import <Cocoa/Cocoa.h>

@interface YKJogWheelView : NSView {

    CGFloat gStartAngle;
    CGFloat gPreAngle;
    NSInteger gRotCount;
}

@end
//
// YKJogWheelView.m
//

#import "YKJogWheelView.h"

@implementation YKJogWheelView

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
    }
    return self;
}

- (void)drawRect:(NSRect)rect {
    // Drawing code here.
}

- (void)setValue:(CGFloat)value
{
    NSLog(@"value = %f", value);
}

- (CGFloat)getAngle:(NSEvent *)theEvent
{
    NSPoint point = [theEvent locationInWindow];
    NSRect frame = [self frame];
    return -atan2(point.y - frame.origin.y - frame.size.height / 2, point.x - frame.origin.x - frame.size.width / 2) / M_PI / 2.0;
}

- (void)setDragEvent:(NSEvent *)theEvent
{
    CGFloat newAngle = [self getAngle:theEvent];
    
    if ((newAngle - gPreAngle) > 0.5) {
        gRotCount--;
    } else if ((newAngle - gPreAngle) < -0.5) {
        gRotCount++;
    }
    
    [self setValue:newAngle - gStartAngle + gRotCount];
    
    gPreAngle = newAngle;
}

- (void)mouseDown:(NSEvent *)theEvent
{
    gStartAngle = [self getAngle:theEvent];
    gRotCount = 0;
    [self setValue:0];
}

- (void)mouseDragged:(NSEvent *)theEvent
{
    [self setDragEvent:theEvent];
}

@end