Draggable CALayer

2019-05-10 16:57发布

问题:

Any way of making a CALayer draggable by the user? If so, how?

(In Cocoa - Mac)

回答1:

Layers can not receive mouse events themselves. You would have to do the event handling in the view or view controller containing the layer.

If a mouseDragged: event originates on a layer (see -[CALayer hitTest:] and -[CALayer containsPoint:] to test this), adjust the layer's position accordingly. You will probably want to disable implicit animations to have the layer follow the mouse pointer immediately (rather than lagging a little behind because of the animation of the position property):

[CATransaction begin];
[CATransaction setDisableActions:YES];
layer.position = ...;
[CATransaction commit];


回答2:

I tried creating a window through code and adding the CALayer to it, but I don't get why it's not showing.

NSRect rect = NSZeroRect;
    rect.size = NSMakeSize( SSRandomFloatBetween( 300.0, 200.0 ), SSRandomFloatBetween( 300.0, 200.0 ));

    NSWindow *newWin = [[NSWindow alloc] initWithContentRect:rect styleMask:NSBorderlessWindowMask backing:NSWindowBackingLocationDefault defer:YES];
    [newWin setBackgroundColor: [NSColor clearColor]];
    [newWin setOpaque:NO];
    [newWin setIgnoresMouseEvents:NO];
    [newWin setMovableByWindowBackground:YES];
    [newWin makeKeyAndOrderFront:self];

    [[newWin contentView] setWantsLayer:YES];

    NSRect contentFrame = [[newWin contentView] frame];
    CALayer *newWinLayer = [CALayer layer];
    newWinLayer.frame = NSRectToCGRect(contentFrame);

    layer.backgroundColor=CGColorCreateGenericGray(0.0f, 0.5f);
    layer.borderColor=CGColorCreateGenericGray(0.756f, 0.5f);
    layer.borderWidth=5.0;

        // Calculate random origin point
    rect.origin = SSRandomPointForSizeWithinRect( rect.size, [window frame] );

        // Set the layer frame to our random rectangle.
    layer.frame = NSRectToCGRect(rect);
    layer.cornerRadius = 25.0f;
  [newWinLayer addSublayer:layer];

Window is linked to a big window, with a semi-transparent (black filled) window that is resized to fill the screen.

I've made the window draggable, but why isn't the CALayer in the window showing?