Layer backed NSView problems in viewDidLoad - macos

I set off to transform an NSImageView. My initially attempt was
self.imageView.wantsLayer = YES;
self.imageView.layer.transform = CATransform3DMakeRotation(1,1,1,1);
Unfortunately I noticed that the transform only happens sometimes (maybe once every 5 runs). Adding an NSLog between confirmed that on some runs self.imageView.layer is null. State of the whole project is shown on the image below.
It's an incredibly simple 200x200 NSImageView with an outlet to a generated NSViewController. Some experimentation showed settings wantsDisplay doesn't fix the problem, but putting the transform on an NSTimer makes it work every-time. I'd love an explanation why this happens (I presume it's due to some race condition).
I'm using Xcode 8 on the macOS 10.12 but I doubt this is the cause of the problem.
Update
Removing wantsLayer and madly enabling Core Animation Layers in Interface Builder did not fix the problem.
Neither did attempts to animate it (I wasn't sure what I was hoping for)
// Sometimes works.. doesn't animate
[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
context.duration = 1;
self.imageView.animator.layer.transform = CATransform3DMakeRotation(1,1,1,1);
} completionHandler:^{
NSLog(#"Done");
}];
or
// Animates but only sometimes
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"transform"];
animation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeRotation(1,1,1,1)];
animation.duration = 1;
[self.imageView.layer addAnimation:animation forKey:nil];

After experimenting with allowsImplicitAnimation I realised I might be trying to animate too early.
Moving the transform code into viewDidAppear made it work every time.
- (void)viewDidAppear {
[super viewDidAppear];
self.imageView.animator.layer.transform = CATransform3DMakeRotation(1,1,1,1);
}

Related

El Capitan broke my NSView animations

I have a Mac app that uses a NSAnimationContext animation grouping to animate one NSView offscreen and another NSView onscreen. Prior to beginning the animation grouping I position the offscreen NSView in the position that I want it to originate from when it animates onscreen.
Under Yosemite and earlier versions this worked perfectly but under El Capitan it is as if the NSView never gets positioned in the start position that I specify so it animates onscreen from the wrong direction.
//Position offscreen view at correct starting point.
offscreenView.frame = STARTING_OFFSCREEN_RECT;
//Create animation grouping
[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration:animationDuration];
[[NSAnimationContext currentContext] setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
[[NSAnimationContext currentContext] setCompletionHandler:^{
/*
Do cleanup stuff here
*/
}];
//Move the views
onscreenView.frame = ENDING_OFFSCREEN_RECT:
offscreenView.frame = ENDING_ONSCREEN_RECT;
//End Grouping
[NSAnimationContext endGrouping];
I've debugged this to the best of my ability and it appears to me that the setting of offscreenView's frame at the very beginning is not actually occurring.
Does anybody know what I'm doing wrong?
I had very similar problem - offscreenView sometimes starts from the wrong position.
The offscreenView.layer appears to be messed up.
I fixed it by adding the following to my clean-up code:
onscreenView.layer = nil;
so that the next time the offscreenView is animated it will start with clean layer.
Or maybe in your case reset the layer before starting the animation:
offscreenView.layer = nil;
//Position offscreen view at correct starting point.
offscreenView.frame = STARTING_OFFSCREEN_RECT;
//Create animation grouping
...
NOTE:
In my animation I add the offscreenView every time to the superView:
//Position offscreen view at correct starting point.
offscreenView.frame = STARTING_OFFSCREEN_RECT;
[superView addSubview:offscreenView];
//Create animation grouping
...
And in the clean-up code I remove the onscreenView as well:
[onscreenView removeFromSuperview];
onscreenView.layer = nil;

NSScrollView and manually setting the content offset while scrolling

I am trying to build an endless NSScrollView, i.e. a scroll view that can scroll infinitely in either direction. This is achieved by having a scroll view with fixed dimension which is 'recentered' once it gets too close to either edge, and keeping track of an additional endless offset that is updated when recentering. Apple even demonstrated this approach in a WWDC video for iOS, if I recall correctly.
On iOS everything is working. I perform the recentering logic in -scrollViewDidScroll: and it even works when the scrolling motion is decelerating without breaking the deceleration.
Now for the Mac version. Let me tell you that I'm fairly new to Mac development, so I may simply not have performed these operations in the correct places. I currently have the recentering logic in -reflectScrolledClipView:. When I perform the move operation immediately, however, the scroll view jumps exactly twice as far as I want it to (in this case, to 4000). If I delay the method slightly, it works just as expected.
- (void)reflectScrolledClipView:(NSClipView *)cView
{
[self recenteringLogic];
[super reflectScrolledClipView:cView];
}
- (void)recenteringLogic
{
CGFloat offset = self.documentVisibleRect.origin.y;
if (offset > 6000) {
// This makes the scroll view jump to ~4000 instead of 5000.
[self performSelector:#selector(move) withObject:nil];
// This works, but seems wrong to me
// [self performSelector:#selector(move) withObject:nil afterDelay:0.0];
}
}
- (void)move
{
[self.documentView scrollPoint:NSMakePoint(0, 4000)];
}
Any ideas on how I could achieve the behavior I want?
Try this:
- (void)scrollWheel:(NSEvent *)event {
[super scrollWheel:event];
[self recenteringLogic];
}
- (void)recenteringLogic
{
NSRect rect = self.documentVisibleRect;
if (rect.origin.y > 6000) {
rect.origin.y = 4000;
[self.contentView setBounds:rect];
}
}
reflectScrolledClipView seemed to be clashing with scrollToPoint somehow, and it caused a stack overflows when used with the [self.contentView setBounds:rect]; method of scrolling.
I ended up working with [self performSelector:#selector(move) withObject:nil afterDelay:0.0]; and haven't encountered any serious issues with it, despite it seeming a little wrong.

Animating an NSStatusItemView

Struggling with this one. I have a custom NSStatusItemView that I'm trying to animate. I've added the following code to my status item view to kick off the animation:
- (void)setAnimated
{
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:#"opacity"];
anim.duration = 1.0;
anim.repeatCount = HUGE_VALF;
anim.autoreverses = YES;
anim.fromValue=[NSNumber numberWithFloat:1.0];
anim.toValue=[NSNumber numberWithFloat:0.0];
[self.layer addAnimation: anim forKey: #"animateOpacity"];
[self setWantsLayer:YES];
[self setNeedsDisplay:YES];
}
When I call this method, nothing happens. Yet if I move this code to my drawRect method, then the view properly animates at launch. Not entirely sure what I need to do to be able to tell it to start animated after the fact but the above method is not doing it and I have no idea why! Any ideas?
Ok answer myself so the googles have record of the answer!
The problem was, kinda of, a lack of understanding of drawRect. When my setAnimated method calls setNeedsDisplay, it calls drawRect again, effectively undoing what is done in the setAnimated method.
There were two things I did to properly fix this. First, I modified the setAnimated method to accept a BOOL argument and set a isAnimated property on the view to that value. I then, in drawRect, check this BOOL value and do the animation if it is set to YES.
Secondly, it seems, you need to call [self setWantsLayer: YES] the first time the view is drawn. So I call this in drawRect the very first time it is run, so that later animation will work.

Layer size/bounds during a core animation

I am working on a Mac app for Mac OS X 10.6+ and need to redraw the contents of a CAOpenGLLayer while an animation is occurring. I think I've read up on all the necessary parts, but it is just not working for me. I set up the animation as follows:
[CATransaction setAnimationDuration:SLIDE_DURATION];
CABasicAnimation *drawAnim = [CABasicAnimation animationWithKeyPath:#"drawIt"];
[drawAnim setFromValue:[NSNumber numberWithFloat:0]];
[drawAnim setToValue:[NSNumber numberWithFloat:1]];
[drawAnim setDuration:SLIDE_DURATION];
[chartView.chartViewLayer addAnimation:drawAnim forKey:#"drawIt"];
chartFrame.origin.x += controlFrame.size.width;
chartFrame.size.width -= controlFrame.size.width;
chartView.chartViewLayer.frame = CGRectMake(chartFrame.origin.x,
chartFrame.origin.y,
chartFrame.size.width,
chartFrame.size.height);
The drawIt property is a custom property whose only purpose is to be called to draw the layer during the successive animation frames. It order to get this to work, you have to add this to the chartViewLayer's class:
+ (BOOL)needsDisplayForKey:(NSString *)key
{
if ([key isEqualToString:#"drawIt"])
{
return YES;
}
else
{
return [super needsDisplayForKey:key];
}
}
So this seems to all be working fine. However, I need to get the current (animated) size of the layer before drawing it. I've found various conflicting information on how to get this out of the presentation layer. Here is what I've tried when the layer's:
drawInCGLContext:(CGLContextObj)glContext
pixelFormat:(CGLPixelFormatObj)pixelFormat
forLayerTime:(CFTimeInterval)timeInterval
displayTime:(const CVTimeStamp *)timeStamp
method is called during the animation. I've tried getting the size using KVC, and by querying either the frame or the bounds.
CALayer *presentationLayer = [chartViewLayer presentationLayer];
//bounds.size.width = [[[chartViewLayer presentationLayer]
// valueForKeyPath:#"frame.size.width"] intValue];
//bounds.size.height = [[[chartViewLayer presentationLayer]
// valueForKeyPath:#"frame.size.height"] intValue];
//bounds.size = presentationLayer.bounds.size;
bounds.size = presentationLayer.frame.size;
NSLog(#"Size during animation: %f, %f", bounds.size.width, bounds.size.height);
In all cases, the returned value is the end result of the animation rather than the transitional values. My understanding is that using the presentationLayer should give the transitional values.
So is this just broken or am I missing some critical step? Thanks for any help.

Explicit animation of NSView using core animation

I'm trying to slide in a NSView using core animation. I think I need to use explicit animation rather than relying on something like [[view animator] setFrame:newFrame]. This is mainly because I need to set the animation delegate in order to take action after the animation is finished.
I have it working just fine using the animator, but as I said, I need to be notified when the animation finishes. My code currently looks like:
// Animate the controlView
NSRect viewRect = [controlView frame];
NSPoint startingPoint = viewRect.origin;
NSPoint endingPoint = startingPoint;
endingPoint.x += viewRect.size.width;
[[controlView layer] setPosition:NSPointToCGPoint(endingPoint)];
CABasicAnimation *controlPosAnim = [CABasicAnimation animationWithKeyPath:#"position"];
[controlPosAnim setFromValue:[NSValue valueWithPoint:startingPoint]];
[controlPosAnim setToValue:[NSValue valueWithPoint:endingPoint]];
[controlPosAnim setDelegate:self];
[[controlView layer] addAnimation:controlPosAnim forKey:#"controlViewPosition"];
This visually works (and I get notified at the end) but it looks like the actual controlView doesn't get moved. If I cause the window to refresh, the controlView disappears. I tried replacing
[[controlView layer] setPosition:NSPointToCGPoint(endingPoint)];
with
[controlView setFrame:newFrame];
and that does cause the view (and layer) to move, but it is corrupting something such that my app dies with a seg fault soon afterwards.
Most of the examples of explicit animation seem to only be moving a CALayer. There must be a way to moving the NSView and also being able to set a delegate. Any help would be appreciated.
Changes made to views take effect at the end of the current run loop. The same goes for any animations applied to layers.
If you animate a view's layer, the view itself is unaffected which is why the view appears to jump back to its original position when the animation completes.
With these two things in mind, you can get the effect you want by setting the view's frame to what you want it to be when the animation is done and then adding an explicit animation to the view's layer.
When the animation begins, it moves the view to the starting position, animates it to the end position and when the animation is done, the view has the frame you specified.
- (IBAction)animateTheView:(id)sender
{
// Calculate start and end points.
NSPoint startPoint = theView.frame.origin;
NSPoint endPoint = <Some other point>;
// We can set the frame here because the changes we make aren't actually
// visible until this pass through the run loop is done.
// Furthermore, this change to the view's frame won't be visible until
// after the animation below is finished.
NSRect frame = theView.frame;
frame.origin = endPoint;
theView.frame = frame;
// Add explicit animation from start point to end point.
// Again, the animation doesn't start immediately. It starts when this
// pass through the run loop is done.
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"position"];
[animation setFromValue:[NSValue valueWithPoint:startPoint]];
[animation setToValue:[NSValue valueWithPoint:endPoint]];
// Set any other properties you want, such as the delegate.
[theView.layer addAnimation:animation forKey:#"position"];
}
Of course, for this code to work you need to make sure both your view and its superview have layers. If the superview doesn't have a layer, you'll get corrupted graphics.
I think you need to call the setPosition at the end (after setting the animation).
Also, I don't think you should animate explicitely the layer of the view, but instead the view itself by using animator and setting the animations. You can use delegates too with animator :)
// create controlPosAnim
[controlView setAnimations:[NSDictionary dictionaryWithObjectsAndKeys:controlPosAnim, #"frameOrigin", nil]];
[[controlView animator] setFrame:newFrame];

Resources