Mavericks Style Tagging - objective-c

I'm quite new to cocoa and I'm trying to find out how I can create something similar to the new tagging UI in Mavericks:
I assume, I'll have to overwrite NSTokenFieldCell to get the coloured dots or an icon on the tags. But how does this popup list work?
Thanks for your help!

Sadly, you'll have to roll your own. Almost all of the drawing taking place in NSTokenFieldCell is private, so adding any kind of ornamental elements would have to be done by you. If I remember correctly, NSTokenFieldCell uses an NSTokenTextView instead of the window's standard field editor. I'm not sure what's different about it, but I think it's mostly to deal with the specialized nature of "tokenizing" attributed strings. I think they just use NSAttachmentCell objects for the graphical tokens, and when the cell receives a -mouseDown: event, they show the menu.
The menu part would actually be pretty easy because you can add images to menu items like so:
NSMenuItem *redItem = [[NSMenuItem alloc] initWithTitle:#"Red"
action:#selector(chooseColorMenuItem:)
keyEquivalent:#""];
// You could add an image from your app's Resources folder:
NSImage *redSwatchImage = [NSImage imageNamed:#"red-menu-item-swatch"];
// ----- or -----
// You could dynamically draw a color swatch and use that as its image:
NSImage *redSwatchImage = [NSImage imageWithSize:NSMakeSize(16.0, 16.0)
flipped:NO
drawingHandler:^BOOL(NSRect dstRect) {
NSRect pathRect = NSInsetRect(dstRect, 0.5, 0.5); // Aligns border to integral values
NSBezierPath *path = [NSBezierPath bezierPathWithOvalInRect:pathRect];
NSColor *fillColor = [NSColor redColor];
NSColor *strokeColor = [fillColor shadowWithLevel:0.5];
[fillColor setFill];
[path fill];
[strokeColor setStroke];
[path stroke];
return YES;
}];
redItem.image = redImage;
With respect to the token drawing stuff, take my info with a grain of salt because Apple's documentation on this stuff is pretty lacking, so everything I'm telling you is from personal struggles, cursing, and head-banging. Anyway, I'm sorry I couldn't bring you better news, but I guess, it is what it is. Good luck.

Related

How to make a smooth, rounded, volume-like OS X window with NSVisualEffectView?

I'm currently trying to make a window that looks like the Volume OS X window:
To make this, I have my own NSWindow (using a custom subclass), which is transparent/titlebar-less/shadow-less, that has a NSVisualEffectView inside its contentView. Here's the code of my subclass to make the content view round:
- (void)setContentView:(NSView *)aView {
aView.wantsLayer = YES;
aView.layer.frame = aView.frame;
aView.layer.cornerRadius = 14.0;
aView.layer.masksToBounds = YES;
[super setContentView:aView];
}
And here's the outcome (as you can see, the corners are grainy, OS X's are way smoother):
Any ideas on how to make the corners smoother? Thanks
Update for OS X El Capitan
The hack I described in my original answer below is not needed on OS X El Capitan anymore. The NSVisualEffectView’s maskImage should work correctly there, if the NSWindow’s contentView is set to be the NSVisualEffectView (it’s not enough if it is a subview of the contentView).
Here’s a sample project: https://github.com/marcomasser/OverlayTest
Original Answer – Only Relevant for OS X Yosemite
I found a way to do this by overriding a private NSWindow method: - (NSImage *)_cornerMask. Simply return an image created by drawing an NSBezierPath with a rounded rect in it to get a look similar to OS X’s volume window.
In my testing I found that you need to use a mask image for the NSVisualEffectView and the NSWindow. In your code, you’re using the view’s layer’s cornerRadius property to get the rounded corners, but you can achieve the same by using a mask image. In my code, I generate an NSImage that is used by both the NSVisualEffectView and the NSWindow:
func maskImage(#cornerRadius: CGFloat) -> NSImage {
let edgeLength = 2.0 * cornerRadius + 1.0
let maskImage = NSImage(size: NSSize(width: edgeLength, height: edgeLength), flipped: false) { rect in
let bezierPath = NSBezierPath(roundedRect: rect, xRadius: cornerRadius, yRadius: cornerRadius)
NSColor.blackColor().set()
bezierPath.fill()
return true
}
maskImage.capInsets = NSEdgeInsets(top: cornerRadius, left: cornerRadius, bottom: cornerRadius, right: cornerRadius)
maskImage.resizingMode = .Stretch
return maskImage
}
I then created an NSWindow subclass that has a setter for the mask image:
class MaskedWindow : NSWindow {
/// Just in case Apple decides to make `_cornerMask` public and remove the underscore prefix,
/// we name the property `cornerMask`.
#objc dynamic var cornerMask: NSImage?
/// This private method is called by AppKit and should return a mask image that is used to
/// specify which parts of the window are transparent. This works much better than letting
/// the window figure it out by itself using the content view's shape because the latter
/// method makes rounded corners appear jagged while using `_cornerMask` respects any
/// anti-aliasing in the mask image.
#objc dynamic func _cornerMask() -> NSImage? {
return cornerMask
}
}
Then, in my NSWindowController subclass I set up the mask image for the view and the window:
class OverlayWindowController : NSWindowController {
#IBOutlet weak var visualEffectView: NSVisualEffectView!
override func windowDidLoad() {
super.windowDidLoad()
let maskImage = maskImage(cornerRadius: 18.0)
visualEffectView.maskImage = maskImage
if let window = window as? MaskedWindow {
window.cornerMask = maskImage
}
}
}
I don’t know what Apple will do if you submit an app with that code to the App Store. You’re not actually calling any private API, you’re just overriding a method that happens to have the same name as a private method in AppKit. How should you know that there’s a naming conflict? 😉
Besides, this fails gracefully without you having to do anything. If Apple changes the way this works internally and the method just won’t get called, your window does not get the nice rounded corners, but everything still works and looks almost the same.
If you’re curious about how I found out about this method:
I knew that the OS X volume indication did what I want to do and I hoped that changing the volume like a madman resulted in noticeable CPU usage by the process that puts that volume indication on screen. I therefore opened Activity Monitor, sorted by CPU usage, activated the filter to only show “My Processes” and hammered my volume up/down keys.
It became clear that coreaudiod and something called BezelUIServer in /System/Library/LoginPlugins/BezelServices.loginPlugin/Contents/Resources/BezelUI/BezelUIServer did something. From looking at the bundle resources for the latter, it was evident that it is responsible for drawing the volume indication. (Note: that process only runs for a short time after it displays something.)
I then used Xcode to attach to that process as soon as it launched (Debug > Attach to Process > By Process Identifier (PID) or Name…, then enter “BezelUIServer”) and changed the volume again. After the debugger was attached, the view debugger let me take a look at the view hierarchy and see that the window was an instance of a NSWindow subclass called BSUIRoundWindow.
Using class-dump on the binary showed that this class is a direct descendant of NSWindow and only implements three methods, whereas one is - (id)_cornerMask, which sounded promising.
Back in Xcode, I used the Object Inspector (right hand side, third tab) to get the address for the window object. Using that pointer I checked what this _cornerMask actually returns by printing its description in lldb:
(lldb) po [0x108500110 _cornerMask]
<NSImage 0x608000070300 Size={37, 37} Reps=(
"NSCustomImageRep 0x608000082d50 Size={37, 37} ColorSpace=NSCalibratedRGBColorSpace BPS=0 Pixels=0x0 Alpha=NO"
)>
This shows that the return value actually is an NSImage, which is the information I needed to implement _cornerMask.
If you want to take a look at that image, you can write it to a file:
(lldb) e (BOOL)[[[0x108500110 _cornerMask] TIFFRepresentation] writeToFile:(id)[#"~/Desktop/maskImage.tiff" stringByExpandingTildeInPath] atomically:YES]
To dig a bit deeper, you can use Hopper Disassembler to disassemble BezelUIServer and AppKit and generate pseudo code to see how the _cornerMask is implemented and used to get a clearer picture of how the internals work. Unfortunately, everything in regard to this mechanism is private API.
I remember doing this sort of thing long before CALayer was around. You use NSBezierPath to make the path.
I don't believe you actually need to subclass NSWindow. The important bit about the window is to initialize the window with NSBorderlessWindowMask and apply the following settings:
[window setAlphaValue:0.5]; // whatever your desired opacity is
[window setOpaque:NO];
[window setHasShadow:NO];
Then you set the contentView of your window to a custom NSView subclass with the drawRect: method overridden similar to this:
// "erase" the window background
[[NSColor clearColor] set];
NSRectFill(self.frame);
// make a rounded rect and fill it with whatever color you like
NSBezierPath* clipPath = [NSBezierPath bezierPathWithRoundedRect:self.frame xRadius:14.0 yRadius:14.0];
[[NSColor blackColor] set]; // your bg color
[clipPath fill];
result (ignore the slider):
Edit: If this method is for whatever reason undesirable, can you not simply assign a CAShapeLayer as your contentView's layer then either convert the above NSBezierPath to CGPath or just construct as a CGPath and assign the path to the layers path?
The "smooth effect" you are referring to is called "Antialiasing". I did a bit of googling and I think you might be the first person who has tried to round the corners of an NSVisualEffectView. You told the CALayer to have a border radius, which will round the corners, but you didn't set any other options. I would try this:
layer.shouldRasterize = YES;
layer.edgeAntialiasingMask = kCALayerLeftEdge | kCALayerRightEdge | kCALayerBottomEdge | kCALayerTopEdge;
Anti-alias diagonal edges of CALayer
https://developer.apple.com/library/mac/documentation/GraphicsImaging/Reference/CALayer_class/index.html#//apple_ref/occ/instp/CALayer/edgeAntialiasingMask
Despite the limitations of NSVisualEffectView not antialiasing edges, here's a kludgey workaround for now that should work for this application of a floating title-less unresizeable window with no shadow - have a child window underneath that draws out just the edges.
I was able to get mine to look like this:
by doing the following:
In a controller holding everything:
- (void) create {
NSRect windowRect = NSMakeRect(100.0, 100.0, 200.0, 200.0);
NSRect behindWindowRect = NSMakeRect(99.0, 99.0, 202.0, 202.0);
NSRect behindViewRect = NSMakeRect(0.0, 0.0, 202.0, 202.0);
NSRect viewRect = NSMakeRect(0.0, 0.0, 200.0, 200.0);
window = [FloatingWindow createWindow:windowRect];
behindAntialiasWindow = [FloatingWindow createWindow:behindWindowRect];
roundedHollowView = [[RoundedHollowView alloc] initWithFrame:behindViewRect];
[behindAntialiasWindow setContentView:roundedHollowView];
[window addChildWindow:behindAntialiasWindow ordered:NSWindowBelow];
backingView = [[NSView alloc] initWithFrame:viewRect];
contentView = [[NSVisualEffectView alloc] initWithFrame:viewRect];
[contentView setWantsLayer:NO];
[contentView setState:NSVisualEffectStateActive];
[contentView setAppearance:
[NSAppearance appearanceNamed:NSAppearanceNameVibrantLight]];
[contentView setMaskImage:[AppDelegate maskImageWithBounds:contentView.bounds]];
[backingView addSubview:contentView];
[window setContentView:backingView];
[window setLevel:NSFloatingWindowLevel];
[window orderFront:self];
}
+ (NSImage *) maskImageWithBounds: (NSRect) bounds
{
return [NSImage imageWithSize:bounds.size flipped:YES drawingHandler:^BOOL(NSRect dstRect) {
NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:bounds xRadius:20.0 yRadius:20.0];
[path setLineJoinStyle:NSRoundLineJoinStyle];
[path fill];
return YES;
}];
}
RoundedHollowView's drawrect looks like this:
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
// "erase" the window background
[[NSColor clearColor] set];
NSRectFill(self.frame);
[[NSColor colorWithDeviceWhite:1.0 alpha:0.7] set];
NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:self.bounds xRadius:20.0 yRadius:20.0];
path.lineWidth = 2.0;
[path stroke];
}
Again, this is a hack and you may need to play with the lineWidth / alpha values depending on the base color you use - in my example if you look really closely or under lighter backgrounds you'll make out the border a bit, but for my own use it feels less jarring than not having any antialiasing.
Keep in mind that the blending mode won't be the same as the native osx yosemite pop-ups like the volume control - those appear to use a different undocumented behindwindow appearance that shows more of a color burn effect.
All kudos to Marco Masser for the most neat solution, there're two useful points:
For smooth rounded corners to work, the NSVisualEffectView must be the root view within view controller.
When using the dark material there are still funny light cropped edges that get very apparent on the dark background. Make your window background transparent to avoid this, window.backgroundColor = NSColor.clearColor().
None of these solutions worked for me on Mojave. However after an hour of research, I found this amazing repo which showcases different window designs. One of the solution looks like the OP's desired look. I tried it and it worked with nicely anti-aliased rounded corners and no titlebar artifact remaining. Here is the working code:
let visualEffect = NSVisualEffectView()
visualEffect.translatesAutoresizingMaskIntoConstraints = false
visualEffect.material = .dark
visualEffect.state = .active
visualEffect.wantsLayer = true
visualEffect.layer?.cornerRadius = 16.0
window?.titleVisibility = .hidden
window?.styleMask.remove(.titled)
window?.backgroundColor = .clear
window?.isMovableByWindowBackground = true
window?.contentView?.addSubview(visualEffect)
Note at the end the contentView.addSubview(visualEffect) instead of contentView = visualEffect. This is one of the key to make it work.

Fill SKShapeNode with pattern image

I'm trying to fill a SKShapeNode with an Image/pattern but I'm still unsuccessfull.
Can you help me solving this or giving me an alternative? I want to create a collidable custom shape (from any SpriteKit kind) filled with a pattern image.
I've tried the following:
UIBezierPath *path = [[UIBezierPath alloc] init];
[path addArcWithCenter:CGPointMake(0.0, 0.0) radius:50.0 startAngle:0.0 endAngle:(M_PI*2.0) clockwise:YES];
SKShapeNode *shape = [[SKShapeNode alloc] init];
UIImage *patternImg = [UIImage imageNamed:#"pattern"];
shape.path = path.CGPath;
shape.fillColor = [[SKColor alloc] initWithCGColor:[[UIColor alloc] initWithPatternImage:patternImg].CGColor];
and also:
shape.fillColor = [[SKColor alloc] initWithPatternImage:[[UIImage alloc] initWithCGImage:[UIImage imageNamed:#"Basketball"].CGImage]];
This works (but it isn't what I'm looking for):
shape.fillColor = [SKColor redColor];
Thank you!
Starting from iOS 8.0 there is fillTexture property in the SKShapeNode.
i had the sample problem in my game, finally my solution was to add a SKSpriteNode as a child of the SKShapeNode and it worked fine.
SKSpriteNode* node = [[SKSpriteNode alloc] initWithImageNamed:#"bombIcon.png"];
node.name = #"bomb";
node.size = CGSizeMake(10, 10);
[self.bombNode addChild:node];
Where self.bombNode is a SKShapeNode.
Hope it helps
You could try to achieve that with SKCropNode. However, I've seen several questions here that SKShapeNode cannot act as maskNode for SKCropNode, but I haven't tested it myself. In this case you probably have to use SKSpriteNode instead of SKShapeNode.
Well, using modern Swift (you're using Swift by now, right?), you could try:
var marbleNode: SKSpriteNode!
Then later, in your init method:
marbleNode = SKSpriteNode(imageNamed: "SmallerSwirl");
marbleNode.physicsBody = SKPhysicsBody(circleOfRadius: 35.0)
marbleNode.physicsBody?.dynamic = true
marbleNode.physicsBody?.affectedByGravity = true
print(marbleNode.physicsBody)
marbleNode.position = CGPointMake(centerPoint.position.x + 10.0, centerPoint.position.y + 10.0)
self.addChild(marbleNode)
Okay, so that gives us a round sprite node to work with. The Sprite node is responsive to physics, because you set up its physics body separately. So far, so good. Now we need to address the glossed-over part, namely the introduction of the SmallerSwirl .png image.
When you set up your project, it included an Assets.xcassets (pronounced, "x c assets") entry. Click on it, then click on the "+" sign at the middle/bottom of the first column, by the word filter. From the menu that appears, select "New Image Set". A new entry labeled "Image" appears. Click on the word "Image" to change it to "SmallerSwirl".
Next to the SmallerSwirl entry, you see blanks labeled 1x, 2x, and 3x. They are for different screen resolutions. Start by dragging your preferred .png image into the 1x square. That image can be named whatever you want it to be named. It doesn't have to be named SmallerSwirl, though it can be. Drag other images to the 2x and 3x slots if you like.
Run, and you should see your preferred image embodied as a sprite, dancing around the screen.

NSTextView with shadow

I'm trying to add a nice looking shadow to a NSTextViews string, I have this Code so far:
NSShadow *textShadow = [[NSShadow alloc] init];
textShadow.shadowColor = [[NSColor blackColor]
colorWithAlphaComponent:0.3];
textShadow.shadowOffset = NSMakeSize(5.0, -5.0);
textShadow.shadowBlurRadius = 3;
NSDictionary *d = #{NSShadowAttributeName : textShadow,
NSFontAttributeName : [NSFont fontWithName:#"Arial Black" size:36.0],
NSStrokeWidthAttributeName : [NSNumber numberWithFloat:-3.0],
NSStrokeColorAttributeName : [NSColor whiteColor]};
[tv setTypingAttributes:d];
all in all this brings up a pretty looking Drop shadow on the right and the bottom of the string in the NSTextView but because the internal drawing mechanism of the textview seems to draw the "fill" of the Characters first and then the stroke around it, the Shadow lays above the fill of the text in the upper left of the Chars, which looks very bad as you can see here(would post an Image but not enough reputation right now 8-/ )
Is there a better way to add the shadow or a way to "raise" the fill color of the String so it lays above the shadow or is this kind of a Bug in the Foundation framework?
Thanks and greetings,
Alex.

Shadowing a UITextview like a UITextField

I have searched apple's documentation and other posts on Stack Overflow, but I'm still having trouble adding a shadow to the inside of a UITextView. I would like to make it look like a UITextField. Here's the code that I've tried.
CALayer *frontLayer = self.frontField.layer;
[frontLayer setBorderColor:CGColorCreate(CGColorSpaceCreateDeviceGray(), nil)];
[frontLayer setBorderWidth:1];
[frontLayer setCornerRadius:5];
[frontLayer setShadowRadius:10.0];
CGSize shadowOffset = {0.0,3.0};
[frontLayer setShadowOffset:shadowOffset];
[frontLayer setShadowOpacity:1];
self.frontField.clipsToBounds = YES;
Where am I going wrong?
Start off simple and try this:
[myTextView.layer setShadowColor:[[UIColor blackColor] CGColor]];
[myTextView.layer setShadowOffset:CGSizeMake(1.0, 1.0)];
[myTextView.layer setShadowOpacity:1.0];
[myTextView.layer setShadowRadius:0.3];
[myTextView.layer.masksToBounds = NO]; //<-- for UITextView!
to optimise performance also add:
view.layer.shadowPath = [UIBezierPath bezierPathWithRect:myTextView.bounds].CGPath;
Then you can add your other properties back in 1 by 1 and see what is causing an issue for you.
According to 25 iOS performance tips & tricks, adding shadow by setting shadowOffset is an expensive operation and affects performance.
Core Animation has to do an offscreen pass to first determine the
exact shape of your view before it can render the drop shadow, which
is a fairly expensive operation.
You can use instead:
myTextView.layer.shadowPath = [[UIBezierPath bezierPathWithRect:view.bounds] CGPath];

Fade effect at top and bottom of NSTableView/NSOutlineView

I'm looking for a way to draw a fade effect on a table view (and outline view, but I think it will be the same) when the content is scrolled. Here is an example from the Fantastical app:
Also a video of a similar fade on QuickLook windows here.
To make this I tried subclassing the scrollview of a tableview with this code:
#define kFadeEffectHeight 15
#implementation FadingScrollView
- (void)drawRect: (NSRect)dirtyRect
{
[super drawRect: dirtyRect];
NSGradient* g = [[NSGradient alloc] initWithStartingColor: [NSColor blackColor] endingColor: [NSColor clearColor]];
NSRect topRect = self.bounds;
topRect.origin.y = self.bounds.size.height - kFadeEffectHeight;
topRect.size.height = kFadeEffectHeight;
NSRect botRect = self.bounds;
botRect.size.height = kFadeEffectHeight;
[NSGraphicsContext saveGraphicsState];
[[NSGraphicsContext currentContext] setCompositingOperation: NSCompositeDestinationAtop];
// Tried every compositing operation and none worked. Please specify wich one I should use if you do it this way
[g drawInRect: topRect angle: 90];
[g drawInRect: botRect angle: 270];
[NSGraphicsContext restoreGraphicsState];
}
...but this didn't fade anything, probably because this is called before the actual table view is drawn. I have no idea on how to do this :(
By the way, both the tableview and the outlineview I want to have this effect are view-based, and the app is 10.7 only.
In Mac OS X (as your question is tagged), there are several gotchas that make this difficult. This especially true on Lion with elastic scrolling.
I've (just today) put together what I think is a better approach than working on the table or outline views directly: a custom NSScrollView subclass, which keeps two "fade views" tiled in the correct place atop its clip view. JLNFadingScrollView can be configured with the desired fade height and color and is free/open source on Github. Please respect the license and enjoy. :-)