How to loop through core animation sublayer array and apply animations in sequence - objective-c

I want to animate through an array of CATextLayers, one after the other. The layers are created and added in a loop. I need to the animation to work like a flip book. Up to now, as a proof of concept, I have Used CABasicAnimations but in order to animate multiple layers in sequence, I think I need one of the other Core Animation options but am not sure which one. Here's the loop adding the sublayers:
- (void) initLayers: (NSString *)endChar
{
CALayer *rootLayer = self.layer;
int counter =0;
for (NSString *element in alphabet) {
NSLog(#"element: %#",element);
NSString *topLayerName = [NSString stringWithFormat:#"TOP_%d_%#",counter,element];
NSString *bottomLayerName = [NSString stringWithFormat:#"BOT_%d_%#",counter,element];
//get index of endchar - indexOfObject
if (element != endChar) { //change to if key value is less than or equal to endchar index value
CATextLayer *topLayer = [CATextLayer layer];
topLayer.name = topLayerName;
[topLayer setAnchorPoint:CGPointMake(0.5f,1.0f)]; // set the anchorpoint for the transform. This affects layer position too
topLayer.bounds = CGRectMake(0.0f, 0.0f, CHARACTER_WIDTH, CHARACTER_HEIGHT/2);
topLayer.string = element;
topLayer.font = solariFont.fontName;
topLayer.fontSize = FONT_SIZE;
topLayer.backgroundColor = [UIColor blackColor].CGColor;
topLayer.position = CGPointMake(30,30);
topLayer.wrapped = NO;
[rootLayer addSublayer:topLayer];
CATextLayer *bottomLayer = [CATextLayer layer];
bottomLayer.name =bottomLayerName;
[bottomLayer setAnchorPoint:CGPointMake(0.5f,0.0f)]; // set the anchorpoint for the transform. This affects layer position too
bottomLayer.bounds = CGRectMake(0.0f,CHARACTER_HEIGHT/4, CHARACTER_WIDTH, CHARACTER_HEIGHT/2);
bottomLayer.string = element;
bottomLayer.font = solariFont.fontName;
bottomLayer.fontSize = FONT_SIZE;
bottomLayer.backgroundColor = [UIColor blackColor].CGColor;
bottomLayer.position = CGPointMake(topLayer.position.x,topLayer.position.y+2);
bottomLayer.wrapped = NO;
[rootLayer addSublayer:bottomLayer];
counter++;
}
}
[self animChars:rootLayer.sublayers];
}
The question is how can I animate the layers one after the other without the animation for every layer happening at the same time? I want to be able to loop through the sublayers array and animate each CATextLayer in sequence. Do I need CATransactions, MediaTiming? I've been through the core animation guide but am none the wiser.

This is very easy actually. You first need to determine the interval between the animations that you want. When you add the layer to the root layer inside the for loop, set the animations media timing's property beginTime with a CGFloat that increments every time the loop fires.
for the animation use a CABasicAnimation... if you don't know how to set one of those up there are plenty of resources on the web.

I did this by giving each animation a key and testing for this in animationDidStop:
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
if (anim ==[topFront animationForKey:#"topCharFlip"]) { ....

Related

Drawing outside content insets with drawGlyphsForGlyphRange

I'm trying to show some extra symbols next to lines in NSTextView, based on text attributes.
I have successfully subclassed NSLayoutManager, but it seems that layout manager can't draw outside the area set by textContainerInset.
Because my text view can potentially have a very long strings, I'm hoping to keep the drawing connected to displaying glyphs. Is there a way to trick the layout manager to be able to draw inside the content insets — or is there another method I use instead of drawGlyphsForGlyphRange?
I have tried calling super before and after drawing, as well as storing and not storing graphics state. I also attempted setDrawsOutsideLineFragment:YES for the glyphs, but with no luck.
Things like Xcode editor itself uses change markers, so I know that this is somehow doable, but it's very possible I'm looking from the wrong place.
My drawing method, simplified:
- (void)drawGlyphsForGlyphRange:(NSRange)glyphsToShow atPoint:(NSPoint)origin {
[super drawGlyphsForGlyphRange:glyphsToShow atPoint:origin];
NSTextStorage *textStorage = self.textStorage;
NSTextContainer *textContainer = self.textContainers[0];
NSRange glyphRange = glyphsToShow;
NSSize offset = self.textContainers.firstObject.textView.textContainerInset;
while (glyphRange.length > 0) {
NSRange charRange = [self characterRangeForGlyphRange:glyphRange actualGlyphRange:NULL], attributeCharRange, attributeGlyphRange;
id attribute = [textStorage attribute:#"Revision" atIndex:charRange.location longestEffectiveRange:&attributeCharRange inRange:charRange];
attributeGlyphRange = [self glyphRangeForCharacterRange:attributeCharRange actualCharacterRange:NULL];
attributeGlyphRange = NSIntersectionRange(attributeGlyphRange, glyphRange);
if (attribute != nil) {
[NSGraphicsContext saveGraphicsState];
NSRect boundingRect = [self boundingRectForGlyphRange:attributeGlyphRange
inTextContainer:textContainer];
// Find the top of the revision
NSPoint point = NSMakePoint(offset.width - 20, offset.height + boundingRect.origin.y + 1.0);
NSString *marker = #"*";
[marker drawAtPoint:point withAttributes:#{
NSForegroundColorAttributeName: NSColor.blackColor;
}];
[NSGraphicsContext restoreGraphicsState];
}
glyphRange.length = NSMaxRange(glyphRange) - NSMaxRange(attributeGlyphRange);
glyphRange.location = NSMaxRange(attributeGlyphRange);
}
}
The answer was much more simple than I anticipated.
You can set lineFragmentPadding for the associated NSTextContainer to make more room for drawing in the margins. This has to be taken into account when setting insets for the text container.

How to detect which CALayer was clicked on?

I'm having a problem detecting which CALayer is being clicked on, as these CALayers have a constant CABasicAnimation moving the x and y positions.
My current code is as follows:
-(void)mouseUp:(NSEvent *)theEvent
{
CGPoint pointInView = NSPointToCGPoint([self convertPoint:[theEvent locationInWindow]fromView:nil]);
CALayer* clickedOn = [(CALayer*) self.layer hitTest:[self.layer convertPoint:pointInView toLayer:self.layer.superlayer]];
int selectedContact = -1;
for (int i = 0; i < [contactLayers count]; i++) {
CALayer* presentationLayer = [contactLayers[i] presentationLayer];
if (presentationLayer == clickedOn) {
selectedContact = i;
break;
}
}
if(selectedContact == -1)
return; //no contact selected;
CALayer* selectedContactLayer = contactLayers[selectedContact];
[selectedContactLayer removeFromSuperlayer];
}
contactLayers is an NSMutableArray containing all the possible CALayers the user can click on.
Every time this runs, i always seems to end up staying -1. I'm using presentationLayer since the CALayers have a CABasicAnimation applied to them. I also tried modelLayer, but this only works if you click on the initial location of each layer.
So just a recap: I have an NSMutableArray of CALayers that all have a CABasicAnimation applied, this array is called contactLayers. When the user clicks on a layer, I need to know what layer they clicked on by setting the index to the appropriate value in the array.
Compute 'clickedOn' by hit testing 'self.layer.presentationLayer', not 'self.layer'

Method to resize CALayer frame on window resize?

I draw a series of images to various CALayer sublayers, then add those sublayers to a superlayer:
- (void)renderImagesFromArray:(NSArray *)array {
CALayer *superLayer = [CALayer layer];
for (id object in array) {
CALayer* subLayer = [CALayer layer];
// Disregard...
NSURL *path = [NSURL fileURLWithPathComponents:#[NSHomeDirectory(), #"Desktop", object]];
NSImage *image = [[NSImage alloc] initWithContentsOfURL:path];
[self positionImage:image layer:subLayer];
subLayer.contents = image;
subLayer.hidden = YES;
[superLayer addSublayer:subLayer];
}
[self.view setLayer:superLayer];
[self.view setWantsLayer:YES];
// Show top layer
CALayer *top = superLayer.sublayers[0];
top.hidden = NO;
}
I then call [self positionImage: layer:] to stretch the CALayer to it's maximum bounds (essentially using the algorithm for the CSS cover property), and position it in the center of the window:
- (void)positionImage:(NSImage *)image layer:(CALayer *)layer{
float imageWidth = image.size.width;
float imageHeight = image.size.height;
float frameWidth = self.view.frame.size.width;
float frameHeight = self.view.frame.size.height;
float aspectRatioFrame = frameWidth/frameHeight;
float aspectRatioImage = imageWidth/imageHeight;
float computedImageWidth;
float computedImageHeight;
float verticalSpace;
float horizontalSpace;
if (aspectRatioImage <= aspectRatioFrame){
computedImageWidth = frameHeight * aspectRatioImage;
computedImageHeight = frameHeight;
verticalSpace = 0;
horizontalSpace = (frameWidth - computedImageWidth)/2;
} else {
computedImageWidth = frameWidth;
computedImageHeight = frameWidth / aspectRatioImage;
horizontalSpace = 0;
verticalSpace = (frameHeight - computedImageHeight)/2;
}
[CATransaction flush];
[CATransaction begin];
CATransaction.disableActions = YES;
layer.frame = CGRectMake(horizontalSpace, verticalSpace, computedImageWidth, computedImageHeight);
[CATransaction commit];
}
This all works fine, except when the window gets resized. I solved this (in a very ugly way) by subclassing NSView, then implementing the only method that was actually called when the window resized, viewWillDraw::
- (void)viewWillDraw{
[super viewWillDraw];
[self redraw];
}
- (void)redraw{
AppDelegate *appDelegate = (AppDelegate *)[[NSApplication sharedApplication] delegate];
CALayer *superLayer = self.layer;
NSArray *sublayers = superLayer.sublayers;
NSImage *image;
CALayer *current;
for (CALayer *view in sublayers){
if (!view.isHidden){
current = view;
image = view.contents;
}
}
[appDelegate positionImage:image layer:current];
}
So... what's the right way to do this? viewWillDraw: get's called too many times which means I have to do unnecessary and redundant calculations, and I can't use viewWillStartLiveResize: because I need to constantly keep the image in its correct position. What am I overlooking?
Peter Hosey was right; my original method was clunky, and I shouldn't have been overriding setNeedsDisplayInRect:. I first made sure that I was using an auto layout in my app, then implemented the following:
subLayer.layoutManager = [CAConstraintLayoutManager layoutManager];
subLayer.autoresizingMask = kCALayerHeightSizable | kCALayerWidthSizable;
subLayer.contentsGravity = kCAGravityResizeAspect;
Basically, I set the sublayer's autoResizingMask to stretch both horizontally and vertically, and then set contentsGravity to preserve the aspect ratio.
That last variable I found by chance, but it's worth noting that you can only use a few contentsGravity constants if, like in my case, you're setting an NSImage as the layer's contents:
That method creates an image that is suited for use as the contents of a layer and that is supports all of the layer’s gravity modes. By contrast, the NSImage class supports only the kCAGravityResize, kCAGravityResizeAspect, and kCAGravityResizeAspectFill modes.
Always fun when a complicated solution can be simplified to 3 lines of code.

image rotation, covers the button

I want to rotate the image around the x-axis from left to right. The problem is that when you rotate the image covers the button located on the top
Run animation
[AnimationUtil rotationRightToLeftForView:image andDuration:1];
Animation metod
+(void) rotationRightToLeftForView:(UIView *)flipView andDuration:(NSTimeInterval)duration{
// Remove existing animations before stating new animation
[flipView.layer removeAllAnimations];
// Make sure view is visible
flipView.hidden = NO;
// show 1/2 animation
//flipView.layer.doubleSided = NO;
// disable the view so it’s not doing anythign while animating
flipView.userInteractionEnabled = NO;
// Set the CALayer anchorPoint to the left edge and
// translate the button to account for the new
// anchorPoint. In case you want to reuse the animation
// for this button, we only do the translation and
// anchor point setting once.
if (flipView.layer.anchorPoint.x != 0.0f) {
flipView.layer.anchorPoint = CGPointMake(0.0f, 0.5f);
flipView.center = CGPointMake(flipView.center.x-flipView.bounds.size.width/2.0f, flipView.center.y);
}
// create an animation to hold the page turning
CABasicAnimation *transformAnimation = [CABasicAnimation animationWithKeyPath:#"transform"];
transformAnimation.removedOnCompletion = NO;
transformAnimation.duration = duration;
transformAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
// start the animation from the current state
transformAnimation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
// this is the basic rotation by 180 degree along the y-axis M_PI
CATransform3D endTransform = CATransform3DMakeRotation(radians(180.0), 0.0f, -1.0f, 0.0f);
transformAnimation.toValue = [NSValue valueWithCATransform3D:endTransform];
// Create an animation group to hold the rotation
CAAnimationGroup *theGroup = [CAAnimationGroup animation];
// Set self as the delegate to receive notification when the animation finishes
theGroup.delegate = self;
theGroup.duration = duration;
// CAAnimation-objects support arbitrary Key-Value pairs, we add the UIView tag
// to identify the animation later when it finishes
[theGroup setValue:[NSNumber numberWithInt:flipView.tag] forKey:#"viewFlipTag"];
// Here you could add other animations to the array
theGroup.animations = [NSArray arrayWithObjects:transformAnimation, nil];
theGroup.removedOnCompletion = NO;
// Add the animation group to the layer
[flipView.layer addAnimation:theGroup forKey:#"flipView"];
}
The decision follows:
Create mask (image) Color = black, make region Size = Button.size Color = transparent
image name = "mask2.png"
button = ...;
ImageView = ...;
parent_view = ...;
UIImage *_maskingImage = [UIImage imageNamed:#"mask2"];
CALayer *_maskingLayer = [CALayer layer];
_maskingLayer.frame = parent_View.bounds;
[_maskingLayer setContents:(id)[_maskingImage CGImage]];
CALayer *layerForImage = [[CALayer alloc] init];
layerForImage.frame = parent_View.bounds;
[layerForImage setMask:_maskingLayer];
[layerForImage addSublayer:ImageView.layer];
[parent_View.layer addSublayer:layerForImage];
[parent_View addSubView:button];

How to add an animated layer at a specific index

I am adding two CAText layers to a view and animating one of them. I want to animate one layer above the other but it doesn't get positioned correctly in the layer hierarchy until the animation has finished. Can anyone see what I have done wrong? The animation works, it is just running behind 'topcharlayer2' until the animation has finished.
- (CABasicAnimation *)topCharFlap
{
CABasicAnimation *flipAnimation;
flipAnimation = [CABasicAnimation animationWithKeyPath:#"transform"];
flipAnimation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeRotation(1.57f, 1, 0, 0)];
flipAnimation.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeRotation(0.0, 1, 0, 0)];
flipAnimation.autoreverses = NO;
flipAnimation.duration = 0.5f;
flipAnimation.repeatCount = 10;
return flipAnimation;
}
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
[self setBackgroundColor:[UIColor clearColor]]; //makes this view transparent other than what is drawn.
[self initChar];
}
return self;
}
static CATransform3D CATransform3DMakePerspective(CGFloat z)
{
CATransform3D t = CATransform3DIdentity;
t.m34 = - 1. / z;
return t;
}
-(void) initChar
{
UIFont *theFont = [UIFont fontWithName:#"AmericanTypewriter" size:FONT_SIZE];
self.layer.sublayerTransform = CATransform3DMakePerspective(-1000.0f);
topHalfCharLayer2 = [CATextLayer layer];
topHalfCharLayer2.bounds = CGRectMake(0.0f, 0.0f, CHARACTERS_WIDTH, 100.0f);
topHalfCharLayer2.string = #"R";
topHalfCharLayer2.font = theFont.fontName;
topHalfCharLayer2.fontSize = FONT_SIZE;
topHalfCharLayer2.backgroundColor = [UIColor blackColor].CGColor;
topHalfCharLayer2.position = CGPointMake(CGRectGetMidX(self.bounds),CGRectGetMidY(self.bounds));
topHalfCharLayer2.wrapped = NO;
topHalfCharLayer1 = [CATextLayer layer];
topHalfCharLayer1.bounds = CGRectMake(0.0f, 0.0f, CHARACTERS_WIDTH, 100.0f);
topHalfCharLayer1.string = #"T";
topHalfCharLayer1.font = theFont.fontName;
topHalfCharLayer1.fontSize = FONT_SIZE;
topHalfCharLayer1.backgroundColor = [UIColor redColor].CGColor;
topHalfCharLayer1.position = CGPointMake(CGRectGetMidX(self.bounds),CGRectGetMidY(self.bounds));
topHalfCharLayer1.wrapped = NO;
//topHalfCharLayer1.zPosition = 100;
[topHalfCharLayer1 setAnchorPoint:CGPointMake(0.5f,1.0f)];
[[self layer] addSublayer:topHalfCharLayer1 ];
[[self layer] insertSublayer:topHalfCharLayer2 atIndex:0];
[topHalfCharLayer1 addAnimation:[self topCharFlap] forKey:#"anythingILikeApparently"];
}
The View which contains this code is loaded by a view controller in loadView. The initChar method is called in the view's initWithFrame method. The target is iOS4. I'm not using setWantsLayer as I've read that UIView in iOS is automatically layer backed and doesn't require this.
A couple thoughts come to mind:
Try adding the 'R' layer to the layer hierarchy before you start the animation.
Instead of inserting the 'T' layer at index 1, use [[self layer] addSublayer: topHalfCharLayer1]; to add it and then do the insert for the 'R' layer with [[self layer] insertSublayer:topHalfCharLayer2 atIndex:0];
Have you tried to play with the layer zPosition? This determines the visual appearance of the layers. It doesn't actually shift the layer order, but will change the way they display--e.g. which layers is in front of/behind which.
I would also suggest you remove the animation code until you get the layer view order sorted. Once you've done that, the animation should just work.
If you have further issues, let me know in the comments.
Best regards.
From the quartz-dev apple mailing list:
Generally in a 2D case, addSublayer will draw the new layer above the
previous. However, I believe this implementation mechanism is
independent of zPosition and probably just uses something like
painter's algorithm. But the moment you add zPositions and 3D, I don't
think you can solely rely on layer ordering. But I am actually unclear
if Apple guarantees anything in the case where you have not set
zPositions on your layers but have a 3D transform matrix set.
So, it seems I have to set the zPosition explicitly when applying 3D transforms to layers.
/* Insert 'layer' at position 'idx' in the receiver's sublayers array.
* If 'layer' already has a superlayer, it will be removed before being
* inserted. */
open func insertSublayer(_ layer: CALayer, at idx: UInt32)