Search code examples
macoscocoacore-animationcalayernsview

NSImageView with CALayer on Top


The goal here is to have a selection layer "on top" of the NSImageView as seen by the user. However, my selection layer keeps ending up at the "back" somehow. Here is my overridden -setImage from my NSImageView subclass:

-(void)setImage:(NSImage *)newImage {

    if(newImage) {

        // compute image location in view

        _imageLocation.x = ( [self frame].size.width - [newImage size].width ) / 2.0;
        _imageLocation.y = ( [self frame].size.height - [newImage size].height ) / 2.0;

        // call to parent
        [super setImage:newImage];

        if(_pixelDataManager) {
            _pixelDataManager = nil;
        }
        _pixelDataManager = [[PixelDataManager alloc] initWithImageForData:newImage];

        _selectionLayer = [CALayer layer];

        [_selectionLayer setBorderColor:[[NSColor yellowColor] CGColor]];

        [_selectionLayer setBorderWidth:2.0];

        [_selectionLayer setCornerRadius:0.0];

        [[self layer] addSublayer:_selectionLayer];

    }
    else {

        [super setImage:nil];
        _pixelDataManager = nil;
        _imageLocation.x = 0.0;
        _imageLocation.y = 0.0;

    }
}

Observe the yellow box behind the image

The focus here is the yellow box. I have similar code for a custom NSView in a different project and that seems OK, but cannot understand why this is not working for NSImageView.


Solution

  • Thanks to mohacs, he/she answered the question in this comment

    you can try changing z order of the layer. http://stackoverflow.com/questions/25371109/z-index-of-image-and-separator-in-uitableviewcell/25372394#25372394 – mohacs Aug 30 '14 at 21:04