Why is this only fading In and not fading out - ios5

I have an image on the UIButton that I wish to glow in when I click button and glow out when I click it again.
Everytime I click, it doesn't glow out, it only glows in making it brighter
.
I have tried UIView animateWithDuration as well as CATransition and CABasicAnimation..
Something is wrong. Probably something basic that I should know about.
I'd appreciate the help.
Heres my code:
-(void)didTapButton:(UIButton *)button {
button.selected = !button.selected;
UIColor *glowColor = [self.arrayOfGlowColor objectAtIndex:button.tag];
UIImageView *imageView = button.imageView;
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, [UIScreen mainScreen].scale);
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0,0,imageView.bounds.size.width,imageView.bounds.size.height)];
[glowColor setFill];
[path fillWithBlendMode:kCGBlendModeSourceAtop alpha:1.0];
UIImage *imageContext_image = UIGraphicsGetImageFromCurrentImageContext();
UIView *glowView = [[UIImageView alloc] initWithImage:imageContext_image];
glowView.center = imageView.center;
[imageView.superview insertSubview:glowView aboveSubview:imageView];
glowView.alpha = 0;
glowView.layer.shadowColor = glowColor.CGColor;
glowView.layer.shadowOffset = CGSizeZero;
glowView.layer.shadowRadius = 10;
glowView.layer.shadowOpacity = 1.0;
/*
[UIView animateWithDuration: 1.0 animations:^(void) {
glowView.alpha = (button.selected) ? 1.0 : 0.0f;
}];
NSLog(#"glowView.alpha:%f",glowView.alpha);
NSLog(button.selected ? #"YES" : #"NO");
*/
/*
if (button.selected) {
CATransition *fadeIn = [CATransition animation];
fadeIn.duration = 1.0;
fadeIn.startProgress = 0.0f;
fadeIn.endProgress = 1.0f;
[fadeIn setType:kCATransitionFade];
fadeIn.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
[fadeIn setFillMode:#"extended"];
[glowView.layer addAnimation:fadeIn forKey:nil];
}
if (!button.selected) {
CATransition *fadeOut = [CATransition animation];
fadeOut.duration = 1.0;
fadeOut.startProgress = 1.0f;
fadeOut.endProgress = 0.0f;
[fadeOut setType:kCATransitionFade];
fadeOut.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
[fadeOut setFillMode:#"extended"];
[glowView.layer addAnimation:fadeOut forKey:nil];
}
*/
if (button.selected) {
//Create a one-way animation that fades in the glow.
glowView.layer.opacity = 1.0;
CABasicAnimation *glowFadeInAnim = [CABasicAnimation animationWithKeyPath:#"opacity"];
glowFadeInAnim.fromValue = [NSNumber numberWithDouble:0.0];
glowFadeInAnim.toValue = [NSNumber numberWithDouble:1.0];
glowFadeInAnim.repeatCount = 1;
glowFadeInAnim.duration = 1.0;
glowFadeInAnim.autoreverses = FALSE;
glowFadeInAnim.fillMode = kCAFillModeForwards;
glowFadeInAnim.removedOnCompletion = NO;
glowFadeInAnim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
[glowView.layer addAnimation:glowFadeInAnim forKey:nil];
}
if (!button.selected) {
glowView.layer.opacity = 1.0;
CABasicAnimation *glowFadeOutAnim = [CABasicAnimation animationWithKeyPath:#"opacity"];
glowFadeOutAnim.fromValue = [NSNumber numberWithDouble:1.0];
glowFadeOutAnim.toValue = [NSNumber numberWithDouble:0.0];
glowFadeOutAnim.repeatCount = 1;
glowFadeOutAnim.beginTime = 2;
glowFadeOutAnim.duration = 2.0;
glowFadeOutAnim.autoreverses = FALSE;
glowFadeOutAnim.fillMode = kCAFillModeForwards;
glowFadeOutAnim.removedOnCompletion = NO;
glowFadeOutAnim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
[glowView.layer addAnimation:glowFadeOutAnim forKey:nil];
glowView.layer.opacity = 0.0;
}
NSLog(#"glowView.opacity:%f",glowView.layer.opacity);
NSLog(button.selected ? #"YES" : #"NO");
}

If you create a new glowView every time the button is pressed and add it to the button, then obviously it will just keep getting brighter, as more and more of them are being added to the button. You need to create the glowView once, for example in your viewDidLoad method, and store it as an instance variable so you don't lose it:
#interface MyViewController : UIViewController {
UIView *_glowView;
}
...
- (void)viewDidLoad {
[super viewDidLoad];
_glowView = ... // Initialise it here
...
[imageView.superview insertSubview:_glowView aboveSubview:imageView];
}
Then in your didTapButton: method, you handle the tap as you do (adding or removing the _glowView, but make sure you don't set it to nil so the reference to it is always retained). This way, you only create and add it once, and the problem should be solved.

Related

Touch position highlight

I'm trying to highlight a touch event by using UIGestureRecognizer, so far I can get the CGPoint where the user touched but I don't know how to highlight that specific area since I don't know much about animation.
The code so far on viewDidLoad:
UITapGestureRecognizer *singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(gradientTouchDown:)];
[self addGestureRecognizer:singleFingerTap];
The method that gets the position of the touch:
-(void)gradientTouchDown:(UIGestureRecognizer*)recognizer{
NSLog(#"tap detected.");
CGPoint point = [recognizer locationInView:nil];
NSLog(#"x = %f y = %f", point.x, point.y );
}
By doing some study I think I need to add the code above with a View animation, but how can I recognize the touch? the code:
[UIView animateWithDuration:0.3f
delay:0.0
options:UIViewAnimationOptionCurveEaseIn
animations:^
{
[sender setAlpha:0.3f];
}
completion:^(BOOL finished)
{
[sender setAlpha:1.0f];
}];
I really need help on this one, any question just ask, I'm always around here :)
This is how I implemented my animation in one of my projects for a button. The animation just puts a glow around the button when pressed (just like the glow you see when you press an year button on the graph view of built in stocks app)
First, add these targets to the button:
[button addTarget:self action:#selector(myButtonPressed:) forControlEvents:UIControlEventTouchDown];
[button addTarget:self action:#selector(myButtonReleased:) forControlEvents:UIControlEventTouchUpInside];
Then these methods looks like this:
- (void) myButtonPressed:(id) sender
{
UIButton *button = (UIButton *) sender;
CABasicAnimation *shadowRadius = [CABasicAnimation animationWithKeyPath:#"shadowRadius" ];
shadowRadius.delegate = self;
[shadowRadius setFromValue:[NSNumber numberWithFloat:3.0]];
[shadowRadius setToValue:[NSNumber numberWithFloat:15.0]];
[shadowRadius setDuration:0.2f];
[[button layer] addAnimation:shadowRadius forKey:#"shadowRadius"];
button.layer.shadowRadius = 15.0f;
}
- (void) myButtonReleased:(id) sender
{
UIButton *button = (UIButton *) sender;
CABasicAnimation *shadowRadius = [CABasicAnimation animationWithKeyPath:#"shadowRadius" ];
shadowRadius.delegate = self;
[shadowRadius setFromValue:[NSNumber numberWithFloat:15.0]];
[shadowRadius setToValue:[NSNumber numberWithFloat:3.0]];
[shadowRadius setDuration:0.2f];
//shadowRadius.autoreverses = YES;
[[button layer] addAnimation:shadowRadius forKey:#"shadowRadius"];
button.layer.shadowRadius = 3.0f;
button.selected = YES;
}
Hi and thanks for the help, I came out with a custom solution for a similar glow effect related to the Apple "Shows Touch on Highlight" here is the code for the glow:
-(void)gradientTouchDown:(UIGestureRecognizer*)recognizer{
NSLog(#"tap detected");
CGPoint point = [recognizer locationInView:nil];
NSLog(#"x = %f y = %f", point.x, point.y );
UIImage* image;
UIColor *color = [UIColor whiteColor];
UIGraphicsBeginImageContextWithOptions(recognizer.view.bounds.size, NO, [UIScreen mainScreen].scale); {
[recognizer.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIBezierPath* path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, recognizer.view.bounds.size.width, recognizer.view.bounds.size.height)];
[color setFill];
[path fillWithBlendMode:kCGBlendModeSourceAtop alpha:1.0];
image = UIGraphicsGetImageFromCurrentImageContext();
} UIGraphicsEndImageContext();
UIView* glowView = [[UIImageView alloc] initWithImage:image];
glowView.center = self.center;
[self.superview insertSubview:glowView aboveSubview:self];
glowView.alpha = 0;
glowView.layer.shadowColor = color.CGColor;
glowView.layer.shadowOffset = CGSizeZero;
glowView.layer.shadowRadius = 10;
glowView.layer.shadowOpacity = 1.0;
CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:#"opacity"];
animation.fromValue = #(0.0f);
animation.toValue = #(0.6f);
//animation.repeatCount = 2 ? HUGE_VAL : 0;
animation.duration = 0.2;
animation.autoreverses = YES;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[glowView.layer addAnimation:animation forKey:#"pulse"];
}
Any suggestion for improvement is welcome, so far it works for me :)

Why is animationDidStart called after removeAllAnimations is called?

In animationDidStart (CABasicAnimation delegate), I want to update a CATextLayer. However, if the user touches the screen, I want to remove all the Animations that are going on by [self.maskLayer removeAllAnimations]; (All my Animations are played sequentially).
However, after removeAllAnimations, somehow, animationDidStart AND animationDidStop are still called, the animation itself is NOT shown. This is NOT what I want, obviously.
The animations are added as follows:
- (void)addAnimations {
for (int i=1; i<6; i++) {
NSString* intValue = [NSString stringWithFormat:#"%d", i];
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"path"];
animation.duration = 0.5;
animation.delegate = self;
animation.repeatCount = 0;
animation.autoreverses = NO;
[animation setValue:intValue forKey:#"animationString"];
animation.timingFunction = nil;
[animation setRemovedOnCompletion:NO];
[animation setFillMode:kCAFillModeForwards];
animation.fromValue = (id) [self getCGRectForZoomLevel:i];
animation.toValue = (id) [self getCGRectForZoomLevel:i + 1 ];
animation.beginTime = CACurrentMediaTime() + i * 2;
[self.shapeLayer addAnimation:animation forKey:intValue];
}
}
How to prevent this? This issue has taken me several hours by now :(
thanks!

Delay an animation – Objective-C

I am using the following code to animate a circle. However, it is constantly blinking. I want to delay the restart of the animation by 5 seconds. How can I do that?
-(void)start
{
[self removeExistingAnimation];
//create the image
UIImage* img = [UIImage imageNamed:#"redCircle.png"];
imageView = [[UIImageView alloc] initWithImage:img];
imageView.frame = CGRectMake(0, 0, 0, 0);
[self addSubview:imageView];
//opacity animation setup
CABasicAnimation *opacityAnimation;
opacityAnimation=[CABasicAnimation animationWithKeyPath:#"opacity"];
opacityAnimation.duration = ANIMATION_DURATION;
opacityAnimation.repeatCount = ANIMATION_REPEAT;
//theAnimation.autoreverses=YES;
opacityAnimation.fromValue = [NSNumber numberWithFloat:0.6];
opacityAnimation.toValue = [NSNumber numberWithFloat:0.025];
//resize animation setup
CABasicAnimation *transformAnimation;
transformAnimation = [CABasicAnimation animationWithKeyPath:#"transform.scale"];
transformAnimation.duration = ANIMATION_DURATION;
transformAnimation.repeatCount = ANIMATION_REPEAT;
//transformAnimation.autoreverses=YES;
transformAnimation.fromValue = [NSNumber numberWithFloat:MIN_RATIO];
transformAnimation.toValue = [NSNumber numberWithFloat:MAX_RATIO];
//group the two animation
CAAnimationGroup *group = [CAAnimationGroup animation];
group.repeatCount = ANIMATION_REPEAT;
[group setAnimations:[NSArray arrayWithObjects:opacityAnimation, transformAnimation, nil]];
group.duration = ANIMATION_DURATION;
//apply the grouped animaton
[imageView.layer addAnimation:group forKey:#"groupAnimation"];
}
Do it like this :
-(void)start
{
[self removeExistingAnimation];
//create the image
UIImage* img = [UIImage imageNamed:#"redCircle.png"];
imageView = [[UIImageView alloc] initWithImage:img];
imageView.frame = CGRectMake(0, 0, 0, 0);
[self addSubview:imageView];
[self doAnimation];
[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(doAnimation) userInfo:nil repeats:YES];
}
-(void)doAnimation
{
//opacity animation setup
CABasicAnimation *opacityAnimation;
opacityAnimation=[CABasicAnimation animationWithKeyPath:#"opacity"];
opacityAnimation.duration = ANIMATION_DURATION;
opacityAnimation.repeatCount = ANIMATION_REPEAT;
//theAnimation.autoreverses=YES;
opacityAnimation.fromValue = [NSNumber numberWithFloat:0.6];
opacityAnimation.toValue = [NSNumber numberWithFloat:0.025];
//resize animation setup
CABasicAnimation *transformAnimation;
transformAnimation = [CABasicAnimation animationWithKeyPath:#"transform.scale"];
transformAnimation.duration = ANIMATION_DURATION;
transformAnimation.repeatCount = ANIMATION_REPEAT;
//transformAnimation.autoreverses=YES;
transformAnimation.fromValue = [NSNumber numberWithFloat:MIN_RATIO];
transformAnimation.toValue = [NSNumber numberWithFloat:MAX_RATIO];
//group the two animation
CAAnimationGroup *group = [CAAnimationGroup animation];
group.repeatCount = ANIMATION_REPEAT;
[group setAnimations:[NSArray arrayWithObjects:opacityAnimation, transformAnimation, nil]];
group.duration = ANIMATION_DURATION;
//apply the grouped animaton
[imageView.layer addAnimation:group forKey:#"groupAnimation"];
}
This is look like dirty method but worked for me , hop it help you..
Isn't this a bit cleaner? Or is there a reason why you can't use blocks for animating?
- (void) start {
//create the image
UIImage* img = [UIImage imageNamed:#"redCircle.png"];
imageView = [[UIImageView alloc] initWithImage:img];
[self addSubview:imageView];
[self animateWithDelay:0.0];
}
- (void) animateWithDelay:(CGFloat)delay {
imageView.alpha = 0.0;
imageView.transfrom = CGAffineTransformScale(myImage.transform, MIN_RATIO, MIN_RATIO);
[UIImageView animateWithDuration:ANIMATION_DURATION delay:delay options:0 animations:^{
imageView.alpha = 1.0;
imageView.transfrom = CGAffineTransformScale(myImage.transform, MAX_RATIO, MAX_RATIO);
} completion:^{
animationCount++;
if (ANIMATION_REPEAT != animationCount) {
[self animateWithDelay:5.0];
}
}];
}
You should define animationCount somewhere in your class, so you know when he should stop repeating.
(Not tested, so could contain some errors)

Animating the drawing of a line

I'm trying to animate the drawing of a line by the following way:
.h
CAShapeLayer *rootLayer;
CAShapeLayer *lineLayer;
CGMutablePathRef path;
.m
path = CGPathCreateMutable();
CGPathMoveToPoint(path, nil, self.frame.size.width/2-100, 260);
CGPathAddLineToPoint(path, nil, self.frame.size.width/2+100.0, 260);
CGPathCloseSubpath(path);
self.rootLayer = [CALayer layer];
rootLayer.frame = self.bounds;
[self.layer addSublayer:rootLayer];
self.lineLayer = [CAShapeLayer layer];
[lineLayer setPath:path];
[lineLayer setFillColor:[UIColor redColor].CGColor];
[lineLayer setStrokeColor:[UIColor blueColor].CGColor];
[lineLayer setLineWidth:1.5];
[lineLayer setFillRule:kCAFillRuleNonZero];
[rootLayer addSublayer:lineLayer];
[self performSelector:#selector(startTotalLine) withObject:nil afterDelay:1.5];
- (void)startTotalLine
{
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"animatePath"];
[animation setDuration:3.5];
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[animation setAutoreverses:NO];
[animation setFromValue:(id)path];
[animation setToValue:(id)path];
[lineLayer addAnimation:animation forKey:#"animatePath"];
}
The line had drawn before the startTotalLine method is invoked.
Also, the startTotalLine method doesn't affect the line.
I want it to animate the the line drawing from right to left.
I would do it with an animated property.
To achieve this I would create a custom CALayer class - let's call it LineLayer. Define a startPoint property, and a length property. I'd then configure the length property to be "animatable".
The code for that would look something like the following:
// LineLayer.h
#interface LineLayer: CALayer
#property (nonatomic, assign) int length;
// This was omitted from the SO code snippet.
#property (nonatomic, assign) CGPoint startPoint;
#end
// LineLayer.m
#implementation LineLayer
#synthesize length = _length;
// This was omitted from the SO code snippet.
#synthesize startPoint= _startPoint;
- (id) initWithLayer:(id)layer
{
if(self = [super initWithLayer:layer])
{
if([layer isKindOfClass:[LineLayer class]])
{
// This bit is required for when we CA is interpolating the values.
LineLayer *other = (LineLayer*)layer;
self.length = other.length;
self.startPoint = other.startPoint; // This was omitted.
}
}
return self;
}
+ (BOOL)needsDisplayForKey:(NSString *)key
{
if ([key isEqualToString:#"length"]) {
return YES;
}
return [super needsDisplayForKey:key];
}
- (void) setLength:(int)newLength
{
if (newLength < 0) {
return; // Fail early.
}
_length = newLength;
[self setNeedsDisplay];
}
/*
This should have been drawInContext:(CGContextRef)context
- (void) drawRect:(CGRect) rect
*/
- (void) drawInContext:(CGContextRef)context
{
//...Do your regular drawing here.
// This was omitted from the SO code snippet.
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextSetLineWidth(context, 2);
CGContextMoveToPoint(context, _startPoint.x, _startPoint.y);
CGContextAddLineToPoint(context, _startPoint.x + _length, _startPoint.y);
CGContextStrokePath(context);
}
#end
Then in your view controller you could use LineLayer like this:
- (void)viewDidLoad
{
[super viewDidLoad];
LineLayer *lineLayer = [LineLayer new];
// This was omitted from the SO code snippet.
lineLayer.frame = CGRectMake(0, 0, 320, 480);
[lineLayer setNeedsDisplay];
// ---
lineLayer.startPoint = CGPointMake(0, 100);
lineLayer.length = 0;
[self.view.layer addSublayer:lineLayer];
// Now animate the changes to the length property
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:#"length"];
anim.duration = 5; // Change should table about 5 mins.
anim.fromValue = [NSNumber numberWithInt:0];
anim.toValue = [NSNumber numberWithInt:200];
[lineLayer addAnimation:anim forKey:#"animateLength"];
lineLayer.length = 200;
//Do clean up below...
}
Happy Coding :)
I think the easiest way to do what you want, is to present some UIView that is 1.5 pixel height and animate it's width. Ask me if I'm not clear.
I think your code doesn't work because your variable path is not a layer property. Read manuals:
CABasicAnimation provides basic, single-keyframe animation
capabilities for a layer property.
And you do something strange here:
[animation setFromValue:(id)path];
[animation setToValue:(id)path];
EDIT:
I stumbled upon an article, and understood what you were try to achieve! Now I think the reason you failed is that you can animate path that doesn't change number of points. And now I thought you can create a path-line with two points. At first they are at same place and another path is the line you want to end up with. Now animate from first path to the second. I think it should work, but I'm not sure.
EDIT:
Definitely! You need this guy's code. Git link.
Here is my solution for your case using "UIBezierPath", "CAShapeLayer" and the property "strokeEnd":
.m file
#synthesize shapeLayer;
[self drawLine];
-(void)drawLine {
CGFloat X1 = self.frame.size.width/2-100;
CGFloat Y1 = 260;
CGFloat X2 = self.frame.size.width/2+100.0;
CGFloat Y2 = 260;
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(X1, Y1)];
[path addLineToPoint:CGPointMake(X2, Y2)];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = [path CGPath];
shapeLayer.strokeColor = [[UIColor blueColor] CGColor];
shapeLayer.lineWidth = 1.5;
shapeLayer.fillColor = [[UIColor redColor] CGColor];
shapeLayer.strokeEnd =0;
[self.layer addSublayer:shapeLayer];
[self performSelector:#selector(startTotalLine) withObject:nil afterDelay:1.5];
}
- (void)startTotalLine {
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"strokeEnd"];
animation.duration = 3.5f;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[animation setAutoreverses:NO];
[animation setFromValue:[NSNumber numberWithInt:0]];
[animation setToValue:[NSNumber numberWithInt:1]];
[shapeLayer addAnimation:animation forKey:#"animatePath"];
}
The default "strokeEnd" value is 1, so, make it 0 at the beginning (no line will appear). Btw, here is useful examples provided: http://jamesonquave.com/blog/fun-with-cashapelayer/

how to get frame of the image while animating from top to bottom of screen using CABasic animation

I am using CABasicAnimation for animating an image from top to bottom of the screen. I need to
get frame of the image while it is animating from top to bottom......
Code:
-(id)init
{
if(self = [super init])
{
self.title =#"Apple Catch";
mView = [[UIView alloc]initWithFrame:CGRectMake(0,0,320,440)];
// start a timet that will fire 20 times per second
[NSTimer scheduledTimerWithTimeInterval:(0.9) target:self selector:#selector(onTimer)
userInfo:nil repeats:YES];
self.view=mView;
}
return self;
}
- (void)onTimer
{
CGImageRef imageRef = [[UIImage imageNamed:#"apple.png"] CGImage];
int startX = round(random() % 460);
double speed = 1 / round(random() %100) + 1.0;
CALayer *layer = [CALayer layer];
layer.name = #"layer";
layer.contents = imageRef;
layer.frame = CGRectMake(startX, self.view.frame.origin.y, CGImageGetWidth(imageRef),
CGImageGetHeight(imageRef));
[mView.layer addSublayer:layer];
CGPoint start = CGPointMake(startX, 0);
CGPoint end = CGPointMake(startX, self.view.frame.size.height+10);
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"position"];
animation.delegate = self;
animation.fromValue = [NSValue valueWithCGPoint:start];
animation.toValue = [NSValue valueWithCGPoint:end];
animation.duration = 10*speed;
//animation.repeatCount = repeatCount;
animation.autoreverses = NO;
animation.removedOnCompletion = YES;
animation.fillMode = kCAFillModeForwards;
[layer addAnimation:animation forKey:#"position"];
BOOL intersects = CGRectIntersectsRect(layer.frame , dragger.frame);
printf("\n ==== intersects value :%d",intersects);
}
I need the frame of the image that is animating at each point of it's path on the view.
Can u please suggest the code for this.
Thank U
Use the presentationLayer property of the CALayer to which the animation is applied.
Hi friend
you can try if (CGRectIntersectsRect(layer.frame,dragger.frame) ) {
nslog(#"hiiii");
}