开发者

Draggable CALayer

Any way of making a CALaye开发者_运维百科r draggable by the user? If so, how?

(In Cocoa - Mac)


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];


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜