6

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!

Eugene Gordin
  • 4,047
  • 3
  • 47
  • 80

4 Answers4

13

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];
Hussain Shabbir
  • 14,801
  • 5
  • 40
  • 56
  • How to set background image for NSImageView Mr.Hussain. I tried to replace colorWithCalibrated with [NSColor colorWithPatternImage:....] in above code, but this doesn't seem to work, please help me, thanks :) – Eshwar Chaitanya Jul 01 '14 at 06:44
  • Why are you using colorWithPatternImage?? – Hussain Shabbir Jul 08 '14 at 16:30
  • @HussainShabbir I want to set background image for NSImageView, I mean I have a letter image and that should be enclosed in a box(image). I could achieve it in ios, however struggling to do so in mac os, [here](http://pastebin.com/d38PMWYY) is my implementation code. Please help me, thanks :) – Eshwar Chaitanya Jul 09 '14 at 06:17
  • @HussainShabbir I solved my problem, thanks for the concern..unlocking focus after returning image solved the issue :) – Eshwar Chaitanya Jul 09 '14 at 06:47
6

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.

Mikael
  • 3,572
  • 1
  • 30
  • 43
1

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
Andre Yonadam
  • 964
  • 1
  • 13
  • 30
0

In swift:

override func draw(_ dirtyRect: NSRect) {
    // Draw Border
    borderColor.set()
    let borderPath = NSBezierPath(rect: dirtyRect)
    borderPath.lineWidth = 2.0
    borderPath.stroke()
}
J.beenie
  • 861
  • 10
  • 22