for example:
label.text = #"I \n love \n stackoverflow ";
how to show those three lines just like first animation fade show "I" , then after animation during time animation fade show "love" finally after animation during time animation fade show "stackoverflow"?
I have created a function for your request. Make sure your label have dynamic height, numberOfLines = 0 and try it ;)
- (void)animateLabel:(UILabel*)label withString:(NSString*)string duration:(NSTimeInterval)duration {
NSUInteger length = [string length];
NSUInteger paraStart = 0, paraEnd = 0, contentsEnd = 0;
NSMutableArray *displayedStringArray = [NSMutableArray array];
NSRange currentRange;
while (paraEnd < length) {
[string getParagraphStart:¶Start end:¶End
contentsEnd:&contentsEnd forRange:NSMakeRange(paraEnd, 0)];
currentRange = NSMakeRange(0, contentsEnd);
[displayedStringArray addObject:[string substringWithRange:currentRange]];
}
CATransition *animation = [CATransition animation];
animation.duration = duration;
animation.type = kCATransitionFade;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
__block void (^animationBlock) (int lineNumber);
__block void (^weakAnimationBlock) (int lineNumber);
animationBlock = ^void(int lineNumber){
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[label.layer addAnimation:animation forKey:#"changeTextTransition"];
label.text = displayedStringArray[lineNumber];
weakAnimationBlock = animationBlock;
__block int nextLine = lineNumber + 1;
if (nextLine < displayedStringArray.count) {
weakAnimationBlock(nextLine);
}
});
};
animationBlock(0);
}
Simply call
[YOUR_CLASS animateLabel:label withString:#"I\nLove\nStackOverFlow" duration:YOUR_DURATION];]
Related
I'm trying to create an infinitely tracing path that draws and the back of it disappears. However, the code I have makes the path disappear after a single iteration. In fact, the layer disappears before the path's disappear animation completes. It seems like, instead, it disappears when the drawing animation completes.
Furthermore, once it disappears, it doesn't show up again for another few seconds (perhaps however long it would take for the animation to repeat) before starting again.
Two questions:
Why is the layer disappearing before the disappearing animation completes?
How can I make the animation play continuously without disappearing?
Thank you in advance! Here's my code:
CGRect boundingFrame = CGRectMake(CGRectGetMidX(self.bounds) - 48.0, CGRectGetMidY(self.bounds) - 48.0, 96.0, 96.0);
_pathPoints = #[
[NSValue valueWithCGPoint:CGPointMake(CGRectGetMidX(boundingFrame), CGRectGetMinY(boundingFrame) + squareSideWidth/2.0)],
[NSValue valueWithCGPoint:CGPointMake(CGRectGetMinX(boundingFrame) + squareSideWidth/2.0, CGRectGetMidY(boundingFrame))],
[NSValue valueWithCGPoint:CGPointMake(CGRectGetMidX(boundingFrame), CGRectGetMaxY(boundingFrame) - squareSideWidth/2.0)],
[NSValue valueWithCGPoint:CGPointMake(CGRectGetMaxX(boundingFrame) - squareSideWidth/2.0, CGRectGetMidY(boundingFrame))]
];
CAShapeLayer *line = [CAShapeLayer layer];
line.path = pathForPoints(_pathPoints).CGPath;
line.lineCap = kCALineCapRound;
line.strokeColor = color.CGColor;
line.fillColor = [UIColor clearColor].CGColor;
line.strokeEnd = 0.0;
[self.layer addSublayer:line];
NSMutableArray<CABasicAnimation *> *animations = [NSMutableArray new];
for (int i = 0; i < [_pathPoints count]; i++) {
CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:#"strokeEnd"];
drawAnimation.beginTime = index;
drawAnimation.duration = 1.0;
drawAnimation.fromValue = #(strokeEndForIndex(points, index - 1));
drawAnimation.toValue = #(strokeEndForIndex(points, index));
drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
drawAnimation.additive = YES;
drawAnimation.removedOnCompletion = NO;
CABasicAnimation *eraseAnimation = [CABasicAnimation animationWithKeyPath:#"strokeStart"];
eraseAnimation.beginTime = index + 0.75;
eraseAnimation.duration = 1.0;
eraseAnimation.fromValue = #(strokeEndForIndex(points, index - 1));
eraseAnimation.toValue = #(strokeEndForIndex(points, index));
eraseAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
eraseAnimation.additive = YES;
eraseAnimation.removedOnCompletion = NO;
CAAnimationGroup *group = [CAAnimationGroup animation];
group.animations = #[drawAnimation, eraseAnimation];
group.duration = 2.0 * [animations count];
group.repeatCount = INFINITY;
group.removedOnCompletion = NO;
[line addAnimation:group forKey:#"line"];
}
Helper functions, for reference:
static CGFloat lengthOfPathWithPoints(NSArray<NSValue *> *points)
{
CGFloat totalDist = 0;
for (int i = 0; i < [points count]; i++) {
CGFloat xDist = [points[i % [points count]] CGPointValue].x - [points[(i + 1) % [points count]] CGPointValue].x;
CGFloat yDist = [points[i % [points count]] CGPointValue].y - [points[(i + 1) % [points count]] CGPointValue].y;
totalDist += sqrt(pow(xDist, 2) + pow(yDist, 2));
}
return totalDist;
}
static CGFloat strokeEndForIndex(NSArray<NSValue *> *points, int index)
{
// If it's the last index, just return 1 early
if (index == [points count] - 1) {
return 1.0;
}
// In the case where index = -1 (as it does for the initial erase animation fromValue), just return 0
if (index < 0) {
return 0.0;
}
CGFloat totalDist = 0;
for (int i = 0; i < index + 1; i++) {
CGFloat xDist = [points[i % [points count]] CGPointValue].x - [points[(i + 1) % [points count]] CGPointValue].x;
CGFloat yDist = [points[i % [points count]] CGPointValue].y - [points[(i + 1) % [points count]] CGPointValue].y;
totalDist += sqrt(pow(xDist, 2) + pow(yDist, 2));
}
return totalDist/lengthOfPathWithPoints(points);
}
static UIBezierPath *pathForPoints(NSArray<NSValue *> *points)
{
UIBezierPath *path = [UIBezierPath new];
[path moveToPoint:[[points firstObject] CGPointValue]];
for (int i = 0; i < [points count]; i++) {
[path addLineToPoint:[points[(i + 1) % 4] CGPointValue]];
}
return path;
}
Increase your duration property value and change your repeatCount = Float(Int.max) to something like this.
I am working on a project in which A video is recorded.When recording is finished, I play video using AVPlayer adding layer to view. Now I want a gif image as adding layer to that view.
I successfully Add gif image as layer, but image is not animated. It is like a static image.I use Library for GIF image.
My code is below
self.avPlayer = [AVPlayer playerWithURL:self.urlstring];
self.avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;
AVPlayerLayer *videoLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
videoLayer.frame = self.preview_view.bounds;
videoLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[self.preview_view.layer addSublayer:videoLayer];
NSURL *url = [[NSBundle mainBundle] URLForResource:#"02" withExtension:#"gif"];
CALayer *layer = [[CALayer alloc]init];
layer.frame = self.img_gif.bounds;
layer.contents = (id) [UIImage animatedImageWithAnimatedGIFData:[NSData dataWithContentsOfURL:url]].CGImage;
[self.preview_view.layer addSublayer:layer];
Please help me with it
Thank you
I have successfully done it. I added my GIF image to layer.
- (CAKeyframeAnimation *)createGIFAnimation:(NSData *)data{
CGImageSourceRef src = CGImageSourceCreateWithData((__bridge CFDataRef)(data), nil);
int frameCount =(int) CGImageSourceGetCount(src);
// Total loop time
float time = 0;
// Arrays
NSMutableArray *framesArray = [NSMutableArray array];
NSMutableArray *tempTimesArray = [NSMutableArray array];
// Loop
for (int i = 0; i < frameCount; i++){
// Frame default duration
float frameDuration = 0.1f;
// Frame duration
CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(src,i,nil);
NSDictionary *frameProperties = (__bridge NSDictionary*)cfFrameProperties;
NSDictionary *gifProperties = frameProperties[(NSString*)kCGImagePropertyGIFDictionary];
// Use kCGImagePropertyGIFUnclampedDelayTime or kCGImagePropertyGIFDelayTime
NSNumber *delayTimeUnclampedProp = gifProperties[(NSString*)kCGImagePropertyGIFUnclampedDelayTime];
if(delayTimeUnclampedProp) {
frameDuration = [delayTimeUnclampedProp floatValue];
} else {
NSNumber *delayTimeProp = gifProperties[(NSString*)kCGImagePropertyGIFDelayTime];
if(delayTimeProp) {
frameDuration = [delayTimeProp floatValue];
}
}
// Make sure its not too small
if (frameDuration < 0.011f){
frameDuration = 0.100f;
}
[tempTimesArray addObject:[NSNumber numberWithFloat:frameDuration]];
// Release
CFRelease(cfFrameProperties);
// Add frame to array of frames
CGImageRef frame = CGImageSourceCreateImageAtIndex(src, i, nil);
[framesArray addObject:(__bridge id)(frame)];
// Compile total loop time
time = time + frameDuration;
}
NSMutableArray *timesArray = [NSMutableArray array];
float base = 0;
for (NSNumber* duration in tempTimesArray){
//duration = [NSNumber numberWithFloat:(duration.floatValue/time) + base];
base = base + (duration.floatValue/time);
[timesArray addObject:[NSNumber numberWithFloat:base]];
}
// Create animation
CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:#"contents"];
animation.duration = time;
animation.repeatCount = HUGE_VALF;
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
animation.values = framesArray;
animation.keyTimes = timesArray;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
animation.calculationMode = kCAAnimationDiscrete;
return animation;
}
To add image in layer of view write below code
CALayer *layer = [CALayer layer];
layer.frame = self.preview_view.bounds;
CAKeyframeAnimation *animation = [self createGIFAnimation:[NSData dataWithContentsOfURL:url]];
[layer addAnimation:animation forKey:#"contents"];
["YOUR VIEW".layer addSublayer:layer];
Try this with your image view.
CALayer *layer = [CALayer layer];
layer.backgroundColor = [[UIColor whiteColor] CGColor];
layer.contents = (id) [UIImage animatedImageWithAnimatedGIFData:[NSData dataWithContentsOfURL:url]].CGImage;
NSURL *url = [[NSBundle mainBundle] URLForResource:#"02" withExtension:#"gif"];
[[self.view layer] addSublayer:layer];
[layer setNeedsDisplay];
[self.view addSubview: animateImageView];
I have a method which translates a view and optionally scales it while translating. I am using animation groups and adding the required animations as needed. Here are the animation cases working perfectly.
Translation (x or y axis or both) (OK)
Scaling (OK)
Translation while scaling (MOSTLY)
However, doing a translation while scaling works only when the starting scalefactor is 1. When the view is already scaled, I notice most of the transition jumping instead of animating, although the end result of scaling and translation is correct.
I am posting part of the code for clarification. The problem occurs only when previousZoomScale is not 1! I appreciate any directions you can point me to.
-(void)performAnimationForView: (AnimationType)animationType
WithDX: (CGFloat)dx
AndDY: (CGFloat)dy
Scale: (CGFloat)scale
Duration: (CGFloat)duration
{
CABasicAnimation *translateXAnimation = nil, *translateYAnimation = nil, *scaleAnimation = nil;
NSString* animationGroupName;
CGPoint newDxDy;
switch (animationType)
{
case kAnimationTranslateAndScale:
// set animation key
animationGroupName = #"translatescale";
translateXAnimation = [CABasicAnimation animationWithKeyPath:#"transform.translation.x"];
translateXAnimation.repeatCount = 0;
translateXAnimation.autoreverses = NO;
translateXAnimation.removedOnCompletion = NO;
translateXAnimation.fillMode = kCAFillModeForwards;
translateXAnimation.fromValue = [NSNumber numberWithFloat: self.previousDxDy.x]; // previous point we're tranlsating from
translateXAnimation.toValue = [NSNumber numberWithFloat:dx]; // destination point
translateYAnimation = [CABasicAnimation animationWithKeyPath:#"transform.translation.y"];
translateYAnimation.repeatCount = 0;
translateYAnimation.autoreverses = NO;
translateYAnimation.removedOnCompletion = NO;
translateYAnimation.fillMode = kCAFillModeForwards;
translateYAnimation.fromValue = [NSNumber numberWithFloat: self.previousDxDy.y];
translateYAnimation.toValue = [NSNumber numberWithFloat:dy];
newDxDy = CGPointMake(dx, dy);
self.previousDxDy = newDxDy;
// scaling animation
scaleAnimation = [CABasicAnimation animationWithKeyPath:#"transform.scale"];
scaleAnimation.autoreverses = NO;
scaleAnimation.repeatCount = 0;
scaleAnimation.removedOnCompletion = NO;
scaleAnimation.fillMode = kCAFillModeForwards;
scaleAnimation.fromValue = [NSNumber numberWithDouble: self.previousZoomScale]; // initial zoom scale
scaleAnimation.toValue = [NSNumber numberWithDouble:scale]; // target scale
self.previousZoomScale = scale;
break;
}
NSMutableArray* animationArray = [[NSMutableArray alloc] initWithObjects: nil];
if (translateXAnimation != nil)
[animationArray addObject: translateXAnimation];
if (translateYAnimation != nil)
[animationArray addObject: translateYAnimation];
if (scaleAnimation != nil)
[animationArray addObject: scaleAnimation];
CAAnimationGroup *theGroup = [CAAnimationGroup animation];
theGroup.duration = duration;
theGroup.removedOnCompletion = NO;
theGroup.fillMode = kCAFillModeForwards;
theGroup.repeatCount = 0;
theGroup.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionLinear];
theGroup.animations = animationArray;
theGroup.delegate = self;
[theGroup setValue: animationGroupName forKey: #"animationtype"];
[self.backgroundImageView.layer addAnimation: theGroup forKey: animationGroupName];
}
I am trying to animate several views (layers) using CAKeyframeAnimation and CAAnimationGroup. Each view to be animated is contained in an array. My idea is to loop through the array where CAKeyframeAnimation instance of each view would be added to an array of animations, which then would be added to the CAAnimationGroup. My goal is to animate each view one after another. As far as I understand I need to use the group in order to have a reference for the beginTime.
I am probably missing something obvious, but my code doesn't work
CAAnimationGroup *cardAnimationGroup = [CAAnimationGroup animation];
cardAnimationGroup.delegate = self;
cardAnimationGroup.removedOnCompletion = NO;
cardAnimationGroup.beginTime = 0.0f;
[cardAnimationGroup setValue:#"animation0" forKey:#"id"];
cardAnimationGroup.duration = 1.2f * [_myViewsArray count];
NSMutableArray *animationsArray = [[NSMutableArray alloc] init];
// Loop through views
for (UIView *cardView in _myViewsArray)
{
NSUInteger index = [_myViewsArray indexOfObject:cardView];
// my target origin
CGFloat yOffset = (-(cardView.frame.origin.y - _middleCardView.frame.origin.y) - index * 2);
CAKeyframeAnimation *translateCardPositionAnimation = [CAKeyframeAnimation animationWithKeyPath:#"transform.translation.y"];
translateCardPositionAnimation.removedOnCompletion = YES;
//translateCardPositionAnimation.fillMode = kCAFillModeForwards;
translateCardPositionAnimation.beginTime = 1.2f * index;
translateCardPositionAnimation.duration = 1.2f;
translateCardPositionAnimation.values = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:0.0f],
[NSNumber numberWithFloat:yOffset],
[NSNumber numberWithFloat:yOffset],nil];
translateCardPositionAnimation.keyTimes = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:0.0f],
[NSNumber numberWithFloat:1.0f],
[NSNumber numberWithFloat:1.2f], nil];
[_containerCardView addSubview:cardView];
[_containerCardView sendSubviewToBack:cardView];
[animationsArray addObject:translateCardPositionAnimation];
[cardView.layer addObject:translateCardPositionAnimation forKey:#"id"];
if (index == [_myViewsArray count]-1) {
[cardAnimationGroup setAnimations:animationsArray];
}
}
I made this code to create CAKeyframeAnimation but result is not bouncing at all
-(CAKeyframeAnimation *)keyframeBounceAnimationFrom:(NSValue *)from
to:(NSValue *)to
forKeypath:(NSString *)keyPath
withDuration:(CFTimeInterval)duration
{
CAKeyframeAnimation * animation = [CAKeyframeAnimation animationWithKeyPath:keyPath];
NSMutableArray * valuesArray = [NSMutableArray array];
NSMutableArray * timeKeyArray = [NSMutableArray array];
[self createBounceFrom:from to:to Values:valuesArray keyTimes:timeKeyArray];
[animation setValues:valuesArray];
[animation setKeyTimes:timeKeyArray];
animation.duration = duration;
return animation;
}
-(void)createBounceFrom:(NSValue *)from to:(NSValue *)to Values:(NSMutableArray *)values keyTimes:(NSMutableArray *)keyTimes
{
CGPoint toPoint= [to CGPointValue];
CGFloat offset = 60;
CGFloat duration = 1.0f;
NSUInteger numberOfOscillations= 4;
[values addObject:from];
[keyTimes addObject:[NSNumber numberWithFloat:0.0f]];
//============
//ideally bouncing will depend from starting position to end poisiton as simulating real Dumping Oscillations
//============
for (NSUInteger index= 0; index <numberOfOscillations ; index++)
{
CGPoint viaPoint = CGPointMake(toPoint.x, toPoint.y + offset);
NSValue * via = [NSValue valueWithCGPoint:viaPoint];
[values addObject:via];
//add time consumed for each oscillation
[keyTimes addObject:[NSNumber numberWithFloat:duration]];
// duration = duration - 0.1;
offset = - offset ;
}
[values addObject:to];
[keyTimes addObject:[NSNumber numberWithFloat:0.6]];
}
Here's a great link with some examples of how to use it:
(After some more looking I found this: http://www.cocoanetics.com/2012/06/lets-bounce/ which I think makes a much better bounce, but more advanced. So wont put the code here)
http://www.touchwonders.com/some-techniques-for-bouncing-animations-in-ios/
The example with CAKeyframeAnimation would be: (taken from the link)
-(void)animateGreenBall
{
NSValue *from = #(greenBall.layer.position.y);
CGFloat bounceDistance = 20.0;
CGFloat direction = (greenUp? 1 : -1);
NSValue *via = #((greenUp ? HEIGHT_DOWN : HEIGHT_UP) + direction*bounceDistance);
NSValue *to = greenUp ? #(HEIGHT_DOWN) : #(HEIGHT_UP);
NSString *keyPath = #"position.y";
CAKeyframeAnimation *animation = [self keyframeBounceAnimationFrom:from
via:via
to:to
forKeyPath:keyPath
withDuration:.6];
[greenBall.layer addAnimation:animation forKey:#"bounce"];
[greenBall.layer setValue:to forKeyPath:keypath];
greenUp = !greenUp;
}
-(CAKeyframeAnimation *)keyframeBounceAnimationFrom:(NSValue *)from
via:(NSValue *)via
to:(NSValue *)to
forKeyPath:(NSString *)keyPath
withDuration:(CFTimeInterval)duration
{
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:keyPath];
[animation setValues:#[from, via, to, nil]];
[animation setKeyTimes:#[#(0), #(.7), #(1), nil]];
animation.duration = duration;
return animation;
}