objective-ccalayernscollectionviewnsimageviewnscollectionviewitem

NSCollectionViewItem selection on NSImageView, border around image with CALayer


I have a NSCollectionViewItem with NSImageView in it.

I want to have a shadow around the image. Once it is selected, I want the image to have shadow and a border. Currently, NSImageView gets a border around the image.

How can I achieve shadow + border on selection? Seems like the border around image sets up correctly, but the border sets up around the image view.

[self.templateImageView setWantsLayer:YES];
self.templateImageView.layer.borderWidth = 0.0;
self.templateImageView.layer.borderColor = borderColor.CGColor;
self.templateImageView.layer.masksToBounds = YES;

[self.templateImageView.layer setShadowColor: [NSColor blackColor].CGColor];
[self.templateImageView.layer setShadowOpacity:0.8];
[self.templateImageView.layer setShadowRadius:5.0];

Solution

  • First, your image must have a transparent background. Then you can draw a border around the content of images:

    func drawOutlie(image:UIImage, color:UIColor) -> UIImage
    {
        let newImageKoef:CGFloat = 1.08
    
        let outlinedImageRect = CGRect(x: 0.0, y: 0.0, width: image.size.width * newImageKoef, height: image.size.height * newImageKoef)
    
        let imageRect = CGRect(x: image.size.width * (newImageKoef - 1) * 0.5, y: image.size.height * (newImageKoef - 1) * 0.5, width: image.size.width, height: image.size.height)
    
        UIGraphicsBeginImageContextWithOptions(outlinedImageRect.size, false, newImageKoef)
    
        image.draw(in: outlinedImageRect)
    
        let context = UIGraphicsGetCurrentContext()
        context!.setBlendMode(CGBlendMode.sourceIn)
    
        context!.setFillColor(color.cgColor)
        context!.fill(outlinedImageRect)
        image.draw(in: imageRect)
    
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    
        return newImage!
    
    }
    

    You can change outline size by changingnewImageKoef.

    The answer is based on haawa answer and update to swift 3.0.