Friday, July 22, 2011

Move Image using UITouch methods in XCode iOS


Declare UIImageView in .h file

UIImageView *imageView;

And rest code will be in .m file

// On Load View Assign image to UIImageView
- (void)viewDidLoad
{
// Get image from resource folder with image name
UIImage *image = [UIImage imageNamed:@"Sample.png"];
// Set Frame size as per image height & width
CGRect frame = CGRectMake(00, image.size.width, image.size.height);
// Allocate memory and set frame for image view
imageView = [[UIImageView allocinitWithFrame: frame];
// Add Image view to main view
[self.view addSubview: imageView];
}

// On touch Image will move to touch location
-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch *touch = [[event allTouchesanyObject];
// Get Touch location
CGPoint touchLocation = [touch locationInView:touch.view];
// Set touch location's center to ImageView
imageView.center = touchLocation;
}

// To Move image with touch You can 
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{
// get touch event
UITouch *touch = [[event allTouchesanyObject];
CGPoint touchLocation = [touch locationInView:self.view];
if ([touch view] == imageView) 
{
// move the image view
imageView.center = touchLocation;
}
}

2 comments:

  1. hi i want to make application like hit the egg to hit the perosn which is walking on road , the egg is thrown user touch direction i want to make this app in native ios app.

    Thnaks in Advance .

    ReplyDelete
  2. really good one..!, i try this the image will moved but the image is not moved slowly left side or right side

    ReplyDelete

Kamleshwar