NSImageView rounded corners + stroke

I have subclasses of NSImageView and I want to draw a border around with rounded corners. It works, but I also need to cut off the corners of the image.

Check out my screenshot:

enter image description here

I created this code to draw border / corners.

- (void)drawRect:(NSRect)dirtyRect { [super drawRect:dirtyRect]; NSColor *strokeColor; if(self.isSelected) strokeColor = [NSColor colorFromHexRGB:@"f9eca2"]; else strokeColor = [NSColor colorFromHexRGB:@"000000"]; [strokeColor set]; [[NSBezierPath bezierPathWithRoundedRect:NSInsetRect(dirtyRect, 1, 1) xRadius:5 yRadius:5] stroke]; } 

What should I do to make an image clip?

EDIT:

Well, I fixed it, but I feel it in an ugly way to do it. Anything smarter?

NEW CODE:

 - (void)drawRect:(NSRect)dirtyRect { NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:NSInsetRect(dirtyRect, 2, 2) xRadius:5 yRadius:5]; [path setLineWidth:4.0]; [path addClip]; [self.image drawAtPoint: NSZeroPoint fromRect:dirtyRect operation:NSCompositeSourceOver fraction: 1.0]; [super drawRect:dirtyRect]; NSColor *strokeColor; if(self.isSelected) { strokeColor = [NSColor colorFromHexRGB:@"f9eca2"]; } else strokeColor = [NSColor colorFromHexRGB:@"000000"]; [strokeColor set]; [NSBezierPath setDefaultLineWidth:4.0]; [[NSBezierPath bezierPathWithRoundedRect:NSInsetRect(dirtyRect, 2, 2) xRadius:5 yRadius:5] stroke]; } 
+6
source share
2 answers

Set the corner radius of your NSImageView layer to 5 pixels, and set its maskToBounds property to YES .

+3
source

updated answer for Xcode 8.3 and Swift 3.1

 import Cocoa class SomeViewController: NSViewController { @IBOutlet weak var artwork: NSImageView! override func viewDidLoad() { super.viewDidLoad() artwork.wantsLayer = true // Use a layer as backing store for this view artwork.canDrawSubviewsIntoLayer = true // Important, flatten all subviews into layer artwork.layer?.cornerRadius = 4.0 artwork.layer?.masksToBounds = true // Mask layer } } 
0
source

Source: https://habr.com/ru/post/909934/


All Articles