Subclass NSProgressIndicator - macos

i like to subclass a NSProgressIndicator. I've used this code and i set the Subclass in the Interface Builder:
- (void)drawRect:(NSRect)dirtyRect {
NSRect rect = NSInsetRect([self bounds], 1.0, 1.0);
CGFloat radius = rect.size.height / 2;
NSBezierPath *bz = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius];
[bz setLineWidth:2.0];
[[NSColor blackColor] set];
[bz stroke];
rect = NSInsetRect(rect, 2.0, 2.0);
radius = rect.size.height / 2;
bz = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius];
[bz setLineWidth:1.0];
[bz addClip];
rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue]));
NSRectFill(rect);
When the app starts its looks like this:
But during the copy progress the old bar shows up.
Whats wrong?

It seems that the progress bar's progress is not drawn in drawRect:, so just overriding drawRect: is not enough. However, if you make the progress bar layer backed, you are responsible for doing all the drawing.
From the documentation:
The view class automatically creates a backing layer for you (using
makeBackingLayer if overridden), and you must use the view class’s
drawing mechanisms.
Check the "Core Animation Layer" in IB or add this to your sub class:
- (void)awakeFromNib {
[super awakeFromNib];
[self setWantsLayer:YES];
}

I followed the above advice (thanks!), but unfortunately discovered that when the NSProgressIndicator was resized, it disappeared, but only on the first viewing (it was inside a drawer).
Rather than try and understand what was happening, I realised you don't actually need the old control, as what I was doing is very simple (a strength indicator that changes color). Just create a subclass of NSView.
So this is it:
#interface SSStrengthIndicator : NSView
/// Set the indicator based upon a score from 0..4
#property (nonatomic) double strengthScore;
#end
#implementation SSStrengthIndicator
- (void)setStrengthScore:(double)strength
{
if (_strengthScore != strength) {
_strengthScore = strength;
[self setNeedsDisplay:YES];
}
}
- (void)drawRect:(NSRect)dirtyRect
{
NSRect rect = NSInsetRect([self bounds], 1.0, 2.0);
double val = (_strengthScore + 1) * 20;
if (val <= 40)
[[NSColor redColor] set];
else if (val <= 60)
[[NSColor yellowColor] set];
else
[[NSColor greenColor] set];
rect.size.width = floor(rect.size.width * (val / 100.0));
[NSBezierPath fillRect:rect];
}
#end

Related

Transparent NSWindow + custom NSView - don't want custom drawn objects to cast shadows?

So I have a borderless window with it's background color set to clear. Inside it, I have an NSView with some custom drawing. It looks like this:
https://www.dropbox.com/s/16dh9ez3z04eic7/Screenshot%202016-02-10%2012.15.35.png?dl=0
The problem is, the custom drawing is casting a shadow, which you can see if the view is hidden:
https://www.dropbox.com/s/04ymp0b2yqi5egu/Screenshot%202016-02-10%2012.19.04.png?dl=0
I only want the shadow around the frame of the window! How can I achieve this?
NOTE: strangely enough, giving the window a title bar provides the behavior I want: https://www.dropbox.com/s/1vv9iwb5403tufe/Screenshot%202016-02-10%2012.25.29.png?dl=0 - Unfortunately, I don't want a title bar.
The code:
#implementation MyWindow
/*
In Interface Builder, the class for the window is set to this subclass. Overriding the initializer
provides a mechanism for controlling how objects of this class are created.
*/
- (id)initWithContentRect:(NSRect)contentRect
styleMask:(NSUInteger)aStyle
backing:(NSBackingStoreType)bufferingType
defer:(BOOL)flag {
self = [super initWithContentRect:contentRect styleMask:NSBorderlessWindowMask backing:bufferingType defer:NO];
if (self != nil) {
[self setOpaque:NO];
[self setBackgroundColor:[NSColor clearColor]];
[self makeKeyAndOrderFront:NSApp];
[self setMovable:YES];
[self setShowsResizeIndicator:YES];
[self setResizeIncrements:NSMakeSize(2, 2)];
[self setLevel:TOP_LEVEL];
}
return self;
}
/*
Custom windows that use the NSBorderlessWindowMask can't become key by default. Override this method
so that controls in this window will be enabled.
*/
- (BOOL)canBecomeKeyWindow {
return YES;
}
#end
And the ContentView:
#implementation WindowContentView
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code here.
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect {
// we need to redraw the whole frame
dirtyRect = self.bounds;
// background
NSBezierPath *framePath = [NSBezierPath bezierPathWithRoundedRect:dirtyRect xRadius:0.0f yRadius:0.0f];
[[NSColor colorWithCalibratedRed:0.0f/255.0f green:255.0f/255.0f blue:153.0f/255.0f alpha:0.3f] setFill];
[framePath fill];
// border
[[NSColor colorWithCalibratedRed:0.0f/255.0f green:255.0f/255.0f blue:153.0f/255.0f alpha:1.0f] setStroke];
framePath.lineWidth = 1.0f;
[framePath stroke];
// grid
[self drawGridInRect:dirtyRect];
[super drawRect:dirtyRect];
}
- (void)drawGridInRect:(NSRect)rect {
int rows = 5;
int columns = 5;
float gridWidth = CGRectGetWidth(rect)/columns;
float gridHeight = CGRectGetHeight(rect)/rows;
[[NSColor colorWithCalibratedRed:0.0f/255.0f green:255.0f/255.0f blue:153.0f/255.0f alpha:0.2f] setStroke];
[NSBezierPath setDefaultLineWidth:1.0f];
for(int i=1; i<rows; i++) {
[NSBezierPath strokeLineFromPoint:NSMakePoint(gridWidth*i, CGRectGetMaxY(rect))
toPoint:NSMakePoint(gridWidth*i, CGRectGetMinY(rect))];
}
for(int i=1; i<columns; i++) {
[NSBezierPath strokeLineFromPoint:NSMakePoint(CGRectGetMaxX(rect), gridHeight*i)
toPoint:NSMakePoint(CGRectGetMinX(rect), gridHeight*i)];
}
}
#end

Shadow in NSScrollView in Mac OS X app

I need two things similar to Pages app in my Mac OS X app. Please view the attached screen shot.
I need a shadow on NSScrollView as shown in Mac OS X Pages app.
I want my scroll bar to be like the one in Mac OS X Pages app.
A quick and easy way of getting the top shadow is to override the enclosing clip view. This is not ideal however, because it draws the shadow (actually a gradient) behind the controls. I find it good enough.
#import <Cocoa/Cocoa.h>
// DFInvertedClipView.h
IB_DESIGNABLE
#interface DFInvertedClipView : NSClipView
#property IBInspectable BOOL shouldDrawTopShadow;
#end
// DFInvertedClipView.m
#import "DFInvertedClipView.h"
#interface DFInvertedClipView ()
#property CGFloat startAlpha;
#end
#implementation DFInvertedClipView
- (BOOL) isFlipped {
return true;
}
-(void) drawRect:(NSRect)dirtyRect
{
[super drawRect:dirtyRect];
if (_shouldDrawTopShadow) {
NSGradient * gradient = [[NSGradient alloc] initWithStartingColor:[NSColor colorWithCalibratedWhite:0.6 alpha:self.startAlpha]
endingColor:[NSColor colorWithCalibratedWhite:0.6 alpha:0.0]];
NSRect b = [self bounds];
NSRect topFade = NSMakeRect(NSMinX(b), NSMinY(b), NSWidth(b), 5.0);
[gradient drawInRect:topFade angle:90];
NSBezierPath *topLine = [NSBezierPath bezierPath];
[topLine moveToPoint:NSMakePoint(NSMinX(self.bounds), NSMinY(self.bounds))];
[topLine lineToPoint:NSMakePoint(NSMaxX(self.bounds), NSMinY(self.bounds))];
CGFloat lineWidth = [[NSScreen mainScreen] backingScaleFactor];
[topLine setLineWidth:lineWidth];
[[NSColor colorWithCalibratedWhite:0.5 alpha:self.startAlpha] setStroke];
[topLine stroke];
}
}
-(void) scrollToPoint:(NSPoint)newOrigin
{
[super scrollToPoint:newOrigin];
// Grade the shadow darkness based on the displacement from a flush fit
CGFloat displacementForFullShadow = 40.0; // pixels
if (newOrigin.y > 0) {
CGFloat alpha = 1.0/displacementForFullShadow * newOrigin.y; // e.g. linear grade function y = m*x + c (m = 1/displacementForFullShadow, c = 0.0)
if (alpha > 1.0) {
alpha = 1.0;
}
self.startAlpha = alpha;
} else {
self.startAlpha = 0.0;
}
}
The shadow of the view above is achieved by setting custom CALayer options of this view (you'll be probably interested in mask-property). Just check the View Effects Inspector from the IB (or you can do it programmatically too - read this)
To remove scroll view knobs' light style open NSScrollView attributes inspector in IB and select Scroller Knobs style to "Default Style" (second line).

Cocoa NSView: Making circles but they are getting cropped

the outer edges of my circle at each point of the compass are getting cropped (presumably by the rect frame). How do I get the circle to display within the frame? (This is getting created from a button click):
In my AppController.m
#import "AppController.h"
#import "MakeCircle.h"
#implementation AppController
- (IBAction)makeCircle:(id)sender {
MakeCircle* newCircle = [[MakeCircle alloc] initWithFrame:NSMakeRect(100.0, 100.0, 30.0, 30.0)];
[[[[NSApplication sharedApplication] mainWindow] contentView] addSubview:newCircle];
[newCircle release];
}
#end
In my MakeCircle.m
- (void)drawRect:(NSRect)rect {
[self setNeedsDisplay:YES];
[[NSColor blackColor] setStroke];
// Create our circle path
NSBezierPath* circlePath = [NSBezierPath bezierPath];
[circlePath appendBezierPathWithOvalInRect: rect];
//give the line some thickness
[circlePath setLineWidth:4];
// Outline and fill the path
[circlePath stroke];
}
Thanks.
I think you see only half of the edge, right? You can calculate the half of the thickness of the edge and subtract that from the rectangle:
#define STROKE_COLOR ([NSColor blackColor])
#define STROKE_WIDTH (4.0)
- (void)drawRect:(NSRect)dirtyRect {
NSBezierPath *path;
NSRect rectangle;
/* Calculate rectangle */
rectangle = [self bounds];
rectangle.origin.x += STROKE_WIDTH / 2.0;
rectangle.origin.y += STROKE_WIDTH / 2.0;
rectangle.size.width -= STROKE_WIDTH / 2.0;
rectangle.size.height -= STROKE_WIDTH / 2.0;
path = [NSBezierPath path];
[path appendBezierPathWithOvalInRect:rectangle];
[path setLineWidth:STROKE_WIDTH];
[STROKE_COLOR setStroke];
[path stroke];
}
I have no Mac at the moment, so I can't test it, but I think it should solve your problem.
Als don't call [self setNeedsDisplay:YES]. The method is used when you want to redraw your whole NSView, and calling it from the drawing method is a little bit recursive. That's why I'm surprised your code actually draws something.
And I have another tip: [[NSApplication sharedApplication] mainWindow] is actually the same as [NSApp mainWindow]. NSApp is a global variable containing the main application.
Hope it helps,
ief2

How do I manage to draw a few images in Custom View and Drag&Drop them

I'm writting a Cocoa app. I've wrote a code that can Drag&Drop one Image. But now I need to draw several Images by double click and D&D them. Each double click- new image, each click on existing image- starts D&D. Problem is in realization. I can't imagine a simple way of realization. Can anybody propose a solution?
Thanks.
#import "DotView.h"
#implementation DotView
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
center.x = center.y = 100.0;
}
return self;
}
- (void)drawRect:(NSRect)rect {
NSRect bounds = [self bounds];
[[NSColor whiteColor] set];
NSRectFill(bounds);
[[NSGraphicsContext currentContext]
setImageInterpolation: NSImageInterpolationHigh];
NSSize viewSize = [self bounds].size;
NSSize imageSize = { 50, 40 };
NSPoint imageOrigin = center;
imageOrigin.x -= imageSize.width * 0.50;
imageOrigin.y -= imageSize.height * 0.50;
NSRect destRect;
destRect.origin = imageOrigin;
destRect.size = imageSize;
NSString * file = #"/Users/classuser/Desktop/ded.jpg";
NSImage * image = [[NSImage alloc] initWithContentsOfFile:file];
[image setFlipped:NO];
[image drawInRect: destRect
fromRect: NSZeroRect
operation: NSCompositeSourceOver
fraction: 1.0];
NSBezierPath * path = [NSBezierPath bezierPathWithRect:destRect];
}
-(void)mouseDown:(NSEvent*)event
{
NSPoint point = [event locationInWindow];
if(center.x<point.x+25 && center.x>point.x-25)
if(center.y<point.y+20 && center.y>point.y-20)
center = [self convertPoint:point fromView:nil];
}
- (void) mouseDragged:(NSEvent*)event {
[self mouseDown:event];
[self setNeedsDisplay:YES];
}
#end
Read:
Cocoa Drawing Guide
and
View Programming Guide for Cocoa
and
Drag and Drop Programming Topics for Cocoa
Once you've read these, ask more targeted questions - this is a bit too broad to answer simply.

Widget "flip" behavior in Core Animation/Cocoa

I'm trying to make a Card class that duplicates the behavior of Dashboard widgets in that you can put controls or images or whatever on two sides of the card and flip between them.
Layer backed views have a transform property, but altering that doesn't do what I would expect it to do (rotating the layer around the y axis folds it off to the left side).
I was pointed to some undocumented features and an .h file named cgsprivate.h, but I'm wondering if there is an official way to do this? This software would have to be shipped and I'd hate to see it fail later because the Apple guys pull it in 10.6.
Anyone have any idea how to do this? It's so weird to me that a simple widget thing would be so hard to do in Core Animation.
Thanks in advance!
EDIT: I can accomplish this behavior with images that are on layers, but I don't know how to get more advanced controls/views/whatever on the layers. The card example uses images.
Mike Lee has an implementation of the flip effect for which he has released some sample code. (Unfortunately, this is no longer available online, but Drew McCormack built off of that in his own implementation.) It appears that he grabs the layers for the "background" and "foreground" views to be swapped, uses a CATransform3D to rotate the two views in the animation, and then swaps the views once the animation has completed.
By using the layers from the views, you avoid needing to cache into a bitmap, since that's what the layers are doing anyways. In any case, his view controller looks to be a good drop-in solution for what you want.
Using Core Animation like e.James outlined...Note, this is using garbage collection and a hosted layer:
#import "AnimationWindows.h"
#interface AnimationFlipWindow (PrivateMethods)
NSRect RectToScreen(NSRect aRect, NSView *aView);
NSRect RectFromScreen(NSRect aRect, NSView *aView);
NSRect RectFromViewToView(NSRect aRect, NSView *fromView, NSView *toView);
#end
#pragma mark -
#implementation AnimationFlipWindow
#synthesize flipForward = _flipForward;
- (id) init {
if ( self = [super init] ) {
_flipForward = YES;
}
return self;
}
- (void) finalize {
// Hint to GC for cleanup
[[NSGarbageCollector defaultCollector] collectIfNeeded];
[super finalize];
}
- (void) flip:(NSWindow *)activeWindow
toBack:(NSWindow *)targetWindow {
CGFloat duration = 1.0f * (activeWindow.currentEvent.modifierFlags & NSShiftKeyMask ? 10.0 : 1.0);
CGFloat zDistance = 1500.0f;
NSView *activeView = [activeWindow.contentView superview];
NSView *targetView = [targetWindow.contentView superview];
// Create an animation window
CGFloat maxWidth = MAX(NSWidth(activeWindow.frame), NSWidth(targetWindow.frame)) + 500;
CGFloat maxHeight = MAX(NSHeight(activeWindow.frame), NSHeight(targetWindow.frame)) + 500;
CGRect animationFrame = CGRectMake(NSMidX(activeWindow.frame) - (maxWidth / 2),
NSMidY(activeWindow.frame) - (maxHeight / 2),
maxWidth,
maxHeight);
mAnimationWindow = [NSWindow initForAnimation:NSRectFromCGRect(animationFrame)];
// Add a touch of perspective
CATransform3D transform = CATransform3DIdentity;
transform.m34 = -1.0 / zDistance;
[mAnimationWindow.contentView layer].sublayerTransform = transform;
// Relocate target window near active window
CGRect targetFrame = CGRectMake(NSMidX(activeWindow.frame) - (NSWidth(targetWindow.frame) / 2 ),
NSMaxY(activeWindow.frame) - NSHeight(targetWindow.frame),
NSWidth(targetWindow.frame),
NSHeight(targetWindow.frame));
[targetWindow setFrame:NSRectFromCGRect(targetFrame) display:NO];
mTargetWindow = targetWindow;
// New Active/Target Layers
[CATransaction begin];
CALayer *activeWindowLayer = [activeView layerFromWindow];
CALayer *targetWindowLayer = [targetView layerFromWindow];
[CATransaction commit];
activeWindowLayer.frame = NSRectToCGRect(RectFromViewToView(activeView.frame, activeView, [mAnimationWindow contentView]));
targetWindowLayer.frame = NSRectToCGRect(RectFromViewToView(targetView.frame, targetView, [mAnimationWindow contentView]));
[CATransaction begin];
[[mAnimationWindow.contentView layer] addSublayer:activeWindowLayer];
[CATransaction commit];
[mAnimationWindow orderFront:nil];
[CATransaction begin];
[[mAnimationWindow.contentView layer] addSublayer:targetWindowLayer];
[CATransaction commit];
// Animate our new layers
[CATransaction begin];
CAAnimation *activeAnim = [CAAnimation animationWithDuration:(duration * 0.5) flip:YES forward:_flipForward];
CAAnimation *targetAnim = [CAAnimation animationWithDuration:(duration * 0.5) flip:NO forward:_flipForward];
[CATransaction commit];
targetAnim.delegate = self;
[activeWindow orderOut:nil];
[CATransaction begin];
[activeWindowLayer addAnimation:activeAnim forKey:#"flip"];
[targetWindowLayer addAnimation:targetAnim forKey:#"flip"];
[CATransaction commit];
}
- (void) animationDidStop:(CAAnimation *)animation finished:(BOOL)flag {
if (flag) {
[mTargetWindow makeKeyAndOrderFront:nil];
[mAnimationWindow orderOut:nil];
mTargetWindow = nil;
mAnimationWindow = nil;
}
}
#pragma mark PrivateMethods:
NSRect RectToScreen(NSRect aRect, NSView *aView) {
aRect = [aView convertRect:aRect toView:nil];
aRect.origin = [aView.window convertBaseToScreen:aRect.origin];
return aRect;
}
NSRect RectFromScreen(NSRect aRect, NSView *aView) {
aRect.origin = [aView.window convertScreenToBase:aRect.origin];
aRect = [aView convertRect:aRect fromView:nil];
return aRect;
}
NSRect RectFromViewToView(NSRect aRect, NSView *fromView, NSView *toView) {
aRect = RectToScreen(aRect, fromView);
aRect = RectFromScreen(aRect, toView);
return aRect;
}
#end
#pragma mark -
#pragma mark CategoryMethods:
#implementation CAAnimation (AnimationFlipWindow)
+ (CAAnimation *) animationWithDuration:(CGFloat)time flip:(BOOL)bFlip forward:(BOOL)forwardFlip{
CABasicAnimation *flipAnimation = [CABasicAnimation animationWithKeyPath:#"transform.rotation.y"];
CGFloat startValue, endValue;
if ( forwardFlip ) {
startValue = bFlip ? 0.0f : -M_PI;
endValue = bFlip ? M_PI : 0.0f;
} else {
startValue = bFlip ? 0.0f : M_PI;
endValue = bFlip ? -M_PI : 0.0f;
}
flipAnimation.fromValue = [NSNumber numberWithDouble:startValue];
flipAnimation.toValue = [NSNumber numberWithDouble:endValue];
CABasicAnimation *shrinkAnimation = [CABasicAnimation animationWithKeyPath:#"transform.scale"];
shrinkAnimation.toValue = [NSNumber numberWithFloat:1.3f];
shrinkAnimation.duration = time * 0.5;
shrinkAnimation.autoreverses = YES;
CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
animationGroup.animations = [NSArray arrayWithObjects:flipAnimation, shrinkAnimation, nil];
animationGroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animationGroup.duration = time;
animationGroup.fillMode = kCAFillModeForwards;
animationGroup.removedOnCompletion = NO;
return animationGroup;
}
#end
#pragma mark -
#implementation NSWindow (AnimationFlipWindow)
+ (NSWindow *) initForAnimation:(NSRect)aFrame {
NSWindow *window = [[NSWindow alloc] initWithContentRect:aFrame
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO];
[window setOpaque:NO];
[window setHasShadow:NO];
[window setBackgroundColor:[NSColor clearColor]];
[window.contentView setWantsLayer:YES];
return window;
}
#end
#pragma mark -
#implementation NSView (AnimationFlipWindow)
- (CALayer *) layerFromWindow {
NSBitmapImageRep *image = [self bitmapImageRepForCachingDisplayInRect:self.bounds];
[self cacheDisplayInRect:self.bounds toBitmapImageRep:image];
CALayer *layer = [CALayer layer];
layer.contents = (id)image.CGImage;
layer.doubleSided = NO;
// Shadow settings based upon Mac OS X 10.6
[layer setShadowOpacity:0.5f];
[layer setShadowOffset:CGSizeMake(0,-10)];
[layer setShadowRadius:15.0f];
return layer;
}
#end
The header file:
#interface AnimationFlipWindow : NSObject {
BOOL _flipForward;
NSWindow *mAnimationWindow;
NSWindow *mTargetWindow;
}
// Direction of flip animation (property)
#property (readwrite, getter=isFlipForward) BOOL flipForward;
- (void) flip:(NSWindow *)activeWindow
toBack:(NSWindow *)targetWindow;
#end
#pragma mark -
#pragma mark CategoryMethods:
#interface CAAnimation (AnimationFlipWindow)
+ (CAAnimation *) animationWithDuration:(CGFloat)time
flip:(BOOL)bFlip // Flip for each side
forward:(BOOL)forwardFlip; // Direction of flip
#end
#interface NSWindow (AnimationFlipWindow)
+ (NSWindow *) initForAnimation:(NSRect)aFrame;
#end
#interface NSView (AnimationFlipWindow)
- (CALayer *) layerFromWindow;
#end
EDIT: This will animate to flip from one window to another window. You can apply the same principals to a view.
It's overkill for your purposes (as it contains a largely-complete board and card game reference app), but check out this sample from ADC. The card games included with it do that flip effect quite nicely.
If you are able to do this with images, perhaps you can keep all of your controls in an NSView object (as usual), and then render the NSView into a bitmap image using cacheDisplayInRect:toBitmapImageRep: just prior to executing the flip effect. The steps would be:
Render the NSView to a bitmap
Display that bitmap in a layer suitable for the flip effect
Hide the NSView and expose the image layer
Perform the flip effect
I know this is late but Apple has an example project here that may be of help to anyone still stumbling upon this question.
https://developer.apple.com/library/mac/#samplecode/ImageTransition/Introduction/Intro.html#//apple_ref/doc/uid/DTS40010277
There's a complete open source implementation of this by the guys at Mizage.
You can check it out here: https://github.com/mizage/Flip-Animation
Probably not the case in 2008 when this question was asked, but this is pretty easy these days:
[UIView animateWithDuration:0.5 animations:^{
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.iconView cache:YES];
/* changes to the view made here will be reflected on the flipped to side */
}];
Note: Apparently, this only works on iOS.

Resources