Adding Borders and Rounded Rect to NSView

In my application, NSView should have a rounded rectangle and a border, I tried to follow

static CGColorRef CGColorCreateFromNSColor (CGColorSpaceRef colorSpace, NSColor *color) { NSColor *deviceColor = [color colorUsingColorSpaceName: NSDeviceRGBColorSpace]; float components[4]; [deviceColor getRed: &components[0] green: &components[1] blue: &components[2] alpha: &components[3]]; return CGColorCreate (colorSpace, components); } 

and the following lines of code are added to InitWithframe

  [[self layer] setCornerRadius:505]; [[self layer] setBorderWidth:500.0]; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB (); CGColorRef cgColor = CGColorCreateFromNSColor (colorSpace, [NSColor whiteColor]); CGColorSpaceRelease (colorSpace); [[self layer] setBorderColor:cgColor]; 

but there are no effects at all, is there any other method,

Another approach I could guess is to draw a border in drawRect, but it seems very difficult if anyone can offer me another method

Yours faithfully

Rohan

+7
source share
3 answers

Thanks for looking at this, this logic worked for me,

 - (void)drawRect:(NSRect)rect { if([self hasBorder]) [self drawBorder:rect]; } -(void)drawBorder:(NSRect)rect{ NSRect frameRect = [self bounds]; if(rect.size.height < frameRect.size.height) return; NSRect newRect = NSMakeRect(rect.origin.x+2, rect.origin.y+2, rect.size.width-3, rect.size.height-3); NSBezierPath *textViewSurround = [NSBezierPath bezierPathWithRoundedRect:newRect xRadius:10 yRadius:10]; [textViewSurround setLineWidth:BORDER_WIDTH]; [pBorderColor set]; [textViewSurround stroke]; } 
+12
source

In order for layer properties to have any effect, you must first set setWantsLayer in NSView to YES.

I have this in InitWithFrame for my view:

 [self setWantsLayer: YES]; [self.layer setBorderWidth: 2]; [self.layer setCornerRadius: 10]; 
+8
source

A slight improvement on the previous answer. If you do not want to subclass NSView, if this is the base view of your controller, you can also do something like this:

 override func viewDidLoad() { super.viewDidLoad() self.view.wantsLayer = true } 
0
source

All Articles