jimwan jimwan - 1 year ago 241
Objective-C Question

How to draw a dash line border for NSView

In my custom view, i have code as below:

- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];

//Drawing code here.
[self setWantsLayer: YES];
[self.layer setBorderWidth: 1];

[self.layer setBorderColor:[NSColor colorWithRed:205/255.0 green:211/255.0 blue:232/255.0 alpha:1.0].CGColor];
[self.layer setCornerRadius: 10];

This is OK to set border line and color for my NSView, but i want to set a dash line, anyone know how to do this?
And i tried some codes from the web search, but it doens't draw a border at all.

- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];

// Drawing code here.
CGFloat dashPattern[] = {10,4}; //make your pattern here
NSBezierPath *textViewSurround = [NSBezierPath bezierPathWithRoundedRect:self.frame xRadius:10 yRadius:10];
[textViewSurround setLineWidth:2.0f];
[textViewSurround setLineDash:dashPattern count:2 phase:0];
[[NSColor colorWithRed:205/255.0 green:211/255.0 blue:232/255.0 alpha:1.0] set];
[textViewSurround stroke];

Answer Source

You can do this like,

[yourView.layer setBorderWidth:5.0];
[yourView.layer setBorderColor:[[UIColor colorWithPatternImage:[UIImage imageNamed:@"DotedImage.png"]] CGColor]];

Add dashed image in project and import QuartzCore/QuartzCore.hin project,

#import <QuartzCore/QuartzCore.h>

Update :

Image size and View size should be same.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download