NSTextView rounded border / stroke in Cocoa - cocoa

I am subclassing NSTextView and over-riding the drawRect method in order to draw an NSBezierPathWithRoundedRect around the textview, however - as it has rounded edges, they interfere with the text in the text view.
Is there any way to apply some kind of margin or padding all around the text input area of the NSTextView so that it is more inset, and away from the rounded edges? Or is a better approach to sit the NSTextView within an NSView and apply the rounded stroke to the NSView instead?
- (void)drawRect:(NSRect)dirtyRect {
// Drawing code here.
[super drawRect:dirtyRect];
NSRect rect = [self bounds];
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:2.0];
[[NSColor whiteColor] set];
[textViewSurround stroke];
}

I think -setTextContainerInset: does what you need. Alternatively, you should not call super in your implementation of -drawRect: and draw the text container yourself.

You could try setting margins on the paragraph style of the whole textView's string.
Or maybe put your textview inside a larger parent view with rounded corners and a border?

Related

Drawing artefact with a NSBackgroundStyleRaised text field when the parent view draws a gradient

Here is a NSView subclass that simply draws a subtle blue gradient (it's hard to see in this image but it is there) in it's bounds. Inside the view I place an NSTextField and set the cell to have NSBackgroundStyleRaised. The artefact is the background of the text field is draws with what looks like the same colour as it's superview. In this case the superview draws a gradient things look strange.
The -drawRect: for the blue view is,
- (void)drawRect:(NSRect)dirtyRect
{
[super drawRect:dirtyRect];
// Base colours
baseColor = [NSColor colorWithCalibratedRed: 0.271 green: 0.578 blue: 0.874 alpha: 1];
baseColorDarkened = [NSColor colorWithCalibratedRed: 0.159 green: 0.491 blue: 0.911 alpha: 1];
// Draw gradient
NSGradient* gradient = [[NSGradient alloc] initWithStartingColor:baseColor endingColor:baseColorDarkened];
NSBezierPath* rectanglePath = [NSBezierPath bezierPathWithRect:dirtyRect];
[gradient drawInBezierPath: rectanglePath angle: 90];
// Draw thin border
NSBezierPath *border = [NSBezierPath bezierPath];
[[baseColorDarkened blendedColorWithFraction:0.2 ofColor:[NSColor blackColor]] set];
[border setLineWidth:1];
[border stroke];
}
I'm using a document based application so in -windowControllerDidLoadNib: I set the properties of the text field,
- (void)windowControllerDidLoadNib:(NSWindowController *)aController
{
[super windowControllerDidLoadNib:aController];
[[_label1 cell] setBackgroundStyle:NSBackgroundStyleLowered];
[_label1 setBackgroundColor:[NSColor clearColor]]; // <-- Doesn't help :(
}
Some background styles seem to require special compositing (probably due to the shadows?).
OS X uses a cached & scaled representation of the superviews background when drawing the NSTextField.
I used your drawing code but changed the top color to make the cached drawing more apparent:
I found 2 workarounds:
Simply enable layer backing on the superview of the label.
When you can't enable layer backing, you could enforce a re-display of the label's superview. e.g. in the NSWindowDelegate method windowDidUpdate:
The second approach feels a bit hacky though:
- (void)windowDidUpdate:(NSNotification*)notification
{
[self.label.superview setNeedsDisplay:YES];
}
Result:

NSTableView with rounded corners

I'm trying to customize the UI of my application and I want my NSTableView to have rounded corners. So I subclassed NSTableView and got this:
However, when I populate the table and select a row, the selection is drawn over the border like this:
I've tried adding a clip in the table view drawing code and it doesn't work. Any suggestions for how I can fix this?
Edit:
My drawing code in the NSTableView is the following:
- (void)drawRect:(NSRect)dirtyRect {
[NSGraphicsContext saveGraphicsState];
NSRect frame = NSMakeRect(0.0, 0.0, [self bounds].size.width, [self bounds].size.height-1.0);
[[NSBezierPath bezierPathWithRoundedRect:frame xRadius:3.6 yRadius:3.6] addClip];
[super drawRect:dirtyRect];
[NSGraphicsContext restoreGraphicsState];
}
The actual rounded frame is drawn in the NSScrollView drawRect method. The interesting thing is that this does clip the selection of the very first and very last rows:
But not when the table is scrolling:
So the question remains: how can I clip all drawing inside the rounded frame of the NSScrollView?
I found that you can call this on the container scroll view of the table view.
self.scrollView.wantsLayer = TRUE;
self.scrollView.layer.cornerRadius = 6;
That's all I needed and it works. No subclassing needed.
I was able to solve this pretty nicely using CALayer. After trying subclassing everything from NSScrollView to NSTableView to NSClipView, and still getting the rendering problems shown above, I finally simply added this code to the drawRect of the NSScrollView subclass:
if (!self.contentView.wantsLayer) {
[self.contentView setWantsLayer:YES];
[self.contentView.layer setCornerRadius:4.0f];
}
And then I draw the frame in the same drawRect method of the NSScrollView. It solves all the problems above.

How to shadow documentView in NSScrollView?

How to shadow documentView in NSScrollView?
The effect look likes iBook Author:
You need to inset the content in your document view to allow space for the shadow to be displayed, then layer back the view and set a shadow on it. Example:
view.wantsLayer = YES;
NSShadow *shadow = [NSShadow new];
shadow.shadowColor = [NSColor blackColor]
shadow.shadowBlurRadius = 4.f;
shadow.shadowOffset = NSMakeSize(0.f, -5.f);
view.shadow = shadow;
The NSScrollView contentView is an NSView subclass, which has a shadow field, if you create a shadow object and assign it to this field, the view will automatically show a drop shadow when drawn
NSShadow* shadow = [[NSShadow alloc] init];
shadow.shadowBlurRadius = 2; //set how many pixels the shadow has
shadow.shadowOffset = NSMakeSize(2, -2); //the distance from the view the shadow is dropped
shadow.shadowColor = [NSColor blackColor];
self.scrollView.contentView.shadow = shadow;
This works because all views when are drawn on drawRect use this shadow property by using [shadow set].
doing [shadow set] during a draw operation makes whatever is drawn after that to be replicated underneath
I'm new to entering posts on stack overflow but I had the same issue and have solved it so I thought after searching the net for hours to find a solution it would be nice to answer it.
My solution is to create a subclass for NSClipView with the following code for drawRect...
- (void)drawRect:(NSRect)dirtyRect
{
[super drawRect:dirtyRect];
NSRect childRect = [[self documentView] frame];
[NSGraphicsContext saveGraphicsState];
// Create the shadow below and to the right of the shape.
NSShadow* theShadow = [[NSShadow alloc] init];
[theShadow setShadowOffset:NSMakeSize(4.0, -4.0)];
[theShadow setShadowBlurRadius:3.0];
// Use a partially transparent color for shapes that overlap.
[theShadow setShadowColor:[[NSColor grayColor]
colorWithAlphaComponent:0.95f]];
[theShadow set];
[[self backgroundColor] setFill];
NSRectFill(childRect);
// Draw your custom content here. Anything you draw
// automatically has the shadow effect applied to it.
[NSGraphicsContext restoreGraphicsState];
}
You then need to create an instance of the subclass and set it with the setContentView selector.
You also need to repaint the clip view every time the content view size changes. If you have your content view set up to change in terms of canvas size when the user wants then unless you repaint the clip view some nasty shadow marks will left behind.
You don't need to mess about with clips as others have suggested.
Hope it helps!

Rounded rect on NSView that clips all containing subviews

I am creating a NSView subclass that has rounded corners. This view is meant to be a container and other subviews will be added to it. I am trying to get the rounded corners of the NSView to clip all of the subview's corners as well, but am not able to get it.
- (void)drawRect:(NSRect)dirtyRect {
NSRect rect = [self bounds];
NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:self.radius yRadius:self.radius];
[path addClip];
[[NSColor redColor] set];
NSRectFill(dirtyRect);
[super drawRect:dirtyRect];
}
The red is just for example. If I add a subview to the rect, The corners are not clipped:
How can I achieve this?
Using Core Animation layers will clip sublayers correctly.
In your container NSView subclass:
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.layer = _layer; // strangely necessary
self.wantsLayer = YES;
self.layer.masksToBounds = YES;
self.layer.cornerRadius = 10.0;
}
return self;
}
You can do it in the interface builder without subclassing adding User Defined Runtime Attributes"
Have you tried clipping with layers?
self.layer.cornerRadius = self.radius;
self.layer.masksToBounds = YES;
Ah, sorry, somehow I've missed that you were talking about NSView, not UIView. It would be hard to clip NSView subviews in all cases because it seems that most of Cocoa standard views set their own clipping path. It might be easier to layout subviews with some paddings and avoid need for clipping.

NSView Not updating?

Im working on a drag n' drop view and found some handlers for drag and drop actions on the web. I want to make it so it turns blue when the user drags a file over the drag and drop area and gray again when they exit the drag and drop area. The issues is its not updating when you drag your mouse over it or exit it. Heres some of the code:
- (void)drawRect:(NSRect)rect
{
NSRect bounds = [self bounds];
[[NSColor grayColor] set];
[NSBezierPath fillRect:bounds];
}
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender {
NSRect bounds = [self bounds];
[[NSColor blueColor] set];
[NSBezierPath fillRect:bounds];
return NSDragOperationCopy;
}
- (void)draggingExited:(id <NSDraggingInfo>)sender {
NSRect bounds = [self bounds];
[[NSColor grayColor] set];
[NSBezierPath fillRect:bounds];
}
Thanks for any help.
Are you calling [yourView: setNeedsDisplay] anywhere?
This is how you let the drawing framework know it needs to message your UIView subclass with drawRect:, so you should do it whenever things have changed. In your case, this probably means when the mouse enters or exits the drop area.
Drawing only works when a context (like a canvas for painting) is set up for you to draw into. When the framework calls -drawRect: it has set up a drawing context for you, so drawing commands like -[NSColor set] and -[NSBezierPath fillRect:] work as you expect.
Outside of -drawRect: there is usually no drawing context set up. Using drawing commands outside of -drawRect: is like waving a paintbrush in the air; there's no canvas, so no painting happens.
In 99.99% of cases, all view drawing should be kept within -drawRect: because NSView does a lot of work that you don't want to do to get the drawing context set up correctly and efficiently.
So, how do you change your view's drawing within your -draggingEntered: and -draggingExited: methods? By side effects.
You're doing the same thing in all three cases: 1) Setting a color and 2) Drawing a rectangle. The only difference is the color changes in each method. So, why not control which color you use in -drawRect: with an ivar, like so:
- (void)draggingEntered:(id <NSDraggingInfo>)sender {
drawBlueColorIvar = YES;
// ...
}
Then in -drawRect: you do this:
- (void)drawRect:(NSRect)rect {
NSColor *color = drawBlueColorIvar ? [NSColor blueColor] : [NSColor grayColor];
[color set];
[NSBezierPath fillRect:rect];
}
(Notice I didn't use [self bounds]. It is more efficient to just draw into the "dirty" rect, when possible.)
Finally, you need some way to tell the framework that your view needs to redraw when drawBlueColorIvar changes. The framework won't draw anything unless it's told it needs to. As Chris Cooper said, you do this with [self setNeedsDisplay:YES]. This should go after any place you change drawBlueColorIvar.

Resources