Load image when screen tapped

152 Views Asked by At

I'm attempting to make an app where you can tape to 'fire' and where you tap it will make an image appear aka a bullet hole. I realise I will have to make a UIImageView appear but I wouldn't have any idea how.

Any help is appreciated

4

There are 4 best solutions below

0
On
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
   UITouch *touch = [[event allTouches] anyObject];
   CGPoint location = [touch locationInView:touch.view];
   NSLog(@"X cord: %f",location.x);
   NSLog(@"Y cord: %f",location.y);
}

On above code you will get the current touch location.So place your image on that location. Hope it will help you.

5
On

Apply a UITapGestureRecognizer to your view controller's view, and set it to perform an action/method where you show the image.

2
On

Make sure your view userInteractionEnabled to YES

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
   UITouch *touch = [[event allTouches] anyObject];
   CGPoint location = [touch locationInView:touch.view];
   [self addBulletHoleImageAtLocation:location];
}

-(void) addBulletHoleImageAtLocation:(CGPoint)location {
   UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(location.x, location.y, yourImageWidth, yourImageHeight)];
   imgView.image = [UIImage imageNamed:@"bulletHole.png"];
   imgView.contentMode = UIViewContentModeCenter;
   [self.view addSubview:imgView];
   [imgView release]; //if NON ARC
}

You can set different contentMode like, UIViewContentModeScaleToFill, UIViewContentModeScaleAspectFit, or UIViewContentModeScaleAspectFillas per your need.

0
On
//
//  ViewController.m
//

#import "ViewController.h"

@implementation ViewController

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView: self.view];

    UIImage *bulletImg = [UIImage imageNamed: @"bullet.png"];
    UIImageView *bulletView = [[UIImageView alloc] initWithImage: bulletImg];

    int bulletWidth = bulletImg.size.width;
    int bulletHeight = bulletImg.size.height;

    bulletView.frame = CGRectMake(
                                  location.x - (bulletWidth / 2), // centered x position
                                  location.y - (bulletHeight / 2), // centered y position
                                  bulletWidth, // width
                                  bulletHeight // height
                                  );

    [self.view addSubview: bulletView];
}

@end