Search code examples
objective-canimationuiimageviewcalayeruitouch

How to add an UIImageView on a CALayer?


Need help. I have been stuck on the problem for many days... I'm doing a touch-to-kill bird-shooting game. When the bird is touched, it dies with an array of images animating its blood splash.. and the bird is static, and sometimes it flies.. i can do the static part easily with the following code:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{UITouch *mytouch=[[touches allObjects] objectAtIndex:0];
   if ([touches count]==1)
   {    
    location = [mytouch locationInView:self];
    UIView *killView = [self hitTest:location withEvent:nil];

    if ([killView isKindOfClass:[UIImageView class]]) {
        birdKilled = YES;
        [self addSubview:[self bloodSplash:killView]];}}}



-(UIImageView *)bloodSplash:(UIView*)killedView {
    UIImageView *blood = [[UIImageView alloc] 
          initWithFrame:CGRectMake(killedView.center.x-100.0/2.0,    killedView.center.y-100.0/2.0, 100, 100)];
    [killedView setHidden:YES];
    blood.image = [bloodExplodes objectAtIndex:2];
    [blood setAnimationImages:bloodExplodes];
    [blood setAnimationDuration:0.4];
    [blood setAnimationRepeatCount:1];
    [blood startAnimating];            
    [self performSelector:@selector(cleanBlood:) withObject:blood afterDelay:.8];
    return [blood autorelease];}

But for the flying part, I'm really stuck! Since I learn that when I animate the flying bird. I need to detect its presentation layer in hitTest. I can do it successfully with "UIViewAnimationOptionAllowUserInteraction" on.. but the problem is I can't figure out how to add the bloodSplash function to the touch point as it returns an UIImageView to a CALayer.. This is my trial...

-(void)touchesBegan:(NSSet *)touches withEvent: (UIEvent *)event{

    if ([flyingBird.layer.presentationLayer hitTest:location]) {
     CALayer* touchedLayer = 
       [flyingBird.layer.presentationLayer hitTest:location];
    //No Idea what to do next..
  }}

Coz I really dunno much about layers..Thx for any advice.


Solution

  • In order to add the image view to your flying bird view you need to find the correct view. A UIView is backed by a CALayer and the layer has the UIView as its delegate. When your animating you need to hitTest on the presentation layer and then go back to the model layer since that is the one relevant to you. From there you can find the corresponding UIView by querying the layer's delegate. So that would look something like this:

    CALayer *hitLayer = [[flyingBird.layer.presentationLayer hitTest:location] modelLayer];
    UIView *hitView = [hitLayer delegate];
    

    This should be the view you can add your animating UIImageView to.