user3614030 user3614030 - 1 year ago 74
iOS Question

How can I simulate a beating heart?

I am making a game and I want the heart to look like it is beating. My approach is to have two images of a heart. One is bigger then the other. I have one as a UIButton (because to start the game I want to click the heart to do so), and the other bigger version of the heart is as UIImageView. So far I have it so the heart changes size every second, but I want it to be more realistic. For example, every second, it will change to the big heart and back (but not instantly so it is clearly visible). How can I do this? Here is my code:


#import <UIKit/UIKit.h>

@interface PlayViewController : UIViewController
IBOutlet UIButton *heartButton;
IBOutlet UIImageView *heartBig;
NSTimer *heartBeat;



#import "PlayViewController.h"

@interface PlayViewController ()


@implementation PlayViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
return self;

- (void)viewDidLoad
[super viewDidLoad];

heartBig.hidden = YES;

heartBeat = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(beatHeart) userInfo:nil repeats:YES];

- (void)didReceiveMemoryWarning
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.

- (void)beatHeart
if(heartBig.hidden == true)
heartBig.hidden = false;

heartBig.hidden = true;


Answer Source

Try this pulse animation:

enter image description here

CABasicAnimation *theAnimation;
theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.scale"];
theAnimation.fromValue=[NSNumber numberWithFloat:1.0];
theAnimation.toValue=[NSNumber numberWithFloat:0.7];
theAnimation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
[self.heart.layer addAnimation:theAnimation forKey:@"animateOpacity"];