Question

I did some research but all the answers I got were for iOS, how can I draw a colored border around NSImage in OSX app? I tried using imageView property of NSImage to set it's border width and color, but it doesn't seem to be working...

Any kind of help is highly appreciated!

Était-ce utile?

La solution

Try like this without creating subclass also it is possible. Also you can set the width ans radius accordingly:-

[imgView setWantsLayer:YES];
imgView.layer.borderWidth = 1.0;
imgView.layer.cornerRadius = 8.0;
imgView.layer.masksToBounds = YES;
CGColorRef color = CGColorRetain([NSColor colorWithCalibratedRed:0 green:100 blue:0 alpha:0.5f].CGColor);
[imgView.layer setBorderColor:color];

Autres conseils

You could subclass NSView and do something like this:

- (void)drawRect:(NSRect)dirtyRect
{
    [[NSColor orangeColor] set];

    NSBezierPath *path = [NSBezierPath bezierPath];
    [path appendBezierPathWithRoundedRect:outerFrame xRadius:5 yRadius:5];
    [path setLineWidth:4.0];
    [path stroke];
}

and of course change the radius values depending if you want rounded corners or not.

In Swift 3:

imagePreview.layer!.borderWidth = 10.0
imagePreview.layer!.cornerRadius = 8.0
imagePreview.layer!.masksToBounds = true
let color: CGColor = NSColor.blue.cgColor
imagePreview.layer!.borderColor = color

In swift:

override func draw(_ dirtyRect: NSRect) {
    // Draw Border
    borderColor.set()
    let borderPath = NSBezierPath(rect: dirtyRect)
    borderPath.lineWidth = 2.0
    borderPath.stroke()
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top