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
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
Apply a UITapGestureRecognizer
to your view controller's view, and set it to perform an action/method where you show the image.
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 UIViewContentModeScaleAspectFill
as per your need.
//
// 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
On above code you will get the current touch location.So place your image on that location. Hope it will help you.