MoveImage in Iphone

This application is a simple drawing, touch handling, and animation using UIKit and Core Animation. A touch inside a placard animates it in two ways: Its transform is changed such that it appears to pulse, and it is moved such that its center is directly under the touch.

This application is a simple drawing, touch handling, and animation using UIKit and Core Animation. A touch inside a placard animates it in two ways: Its transform is changed such that it appears to pulse, and it is moved such that its center is directly under the touch.

Step 1: Create a new project in Xcode using Window base Application. Give it name  MoveApplication.

Step 2: Now we need to add some files into our project. Add-> new file-> select UIView subclass -> give the name PlacardView and save it.

Step 3: Do it once again and save it to the MoveApplication.

Step 4: Add code in your PlacardView.h file.

header file.

#import <UIKit/UIKit.h>

@interface PlacardView : UIView {
UIImage *placardImage;
NSString *currentDisplayString;
CGFloat fontSize;
CGSize textSize;

NSArray *displayStrings;
NSUInteger displayStringsIndex;
}

@property (nonatomic, retain) UIImage *placardImage;
@property (nonatomic, retain) NSString *currentDisplayString;
@property (nonatomic, retain) NSArray *displayStrings;

- (id)init;
- (void)setupNextDisplayString;

Step 5: Impliment two method in the PlacardView.m file.

- (id)init {
// Retrieve the image for the view and determine its size
UIImage *image = [UIImage imageNamed:@"Placard.png"];
CGRect frame = CGRectMake(0, 0, image.size.width, image.size.height);

// Set self’s frame to encompass the image
if (self = [self initWithFrame:frame]) {

self.opaque = NO;
placardImage = image;

// Load the display strings
NSString *path = [[NSBundle mainBundle] pathForResource:@"DisplayStrings" ofType:@"strings"];
NSString *string = [NSString stringWithContentsOfFile:path encoding:NSUTF16BigEndianStringEncoding error:NULL];
self.displayStrings = [string componentsSeparatedByString:@"\n"];
displayStringsIndex = 0;
[self setupNextDisplayString];
}
return self;
}

- (void)setupNextDisplayString {

// Get the string at the current index, then increment the index
self.currentDisplayString = [displayStrings objectAtIndex:displayStringsIndex];
displayStringsIndex++;
if (displayStringsIndex &gt;= [displayStrings count]) {
displayStringsIndex = 0;
}

UIFont *font = [UIFont systemFontOfSize:24];
// Precalculate size of text and size of font so that text fits inside placard
textSize = [currentDisplayString sizeWithFont:font minFontSize:9.0 actualFontSize:&amp;fontSize forWidth:(self.bounds.size.width-STRING_INDENT) lineBreakMode:UILineBreakModeMiddleTruncation];

[self setNeedsDisplay];
}

Step 6: Now we are impliment touch function in our MoveApplicationView.m file.

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

UITouch *touch = [touches anyObject];

// If the touch was in the placardView, move the placardView to its location
if ([touch view] == placardView) {
CGPoint location = [touch locationInView:self];
placardView.center = location;
return;
}
}

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

UITouch *touch = [touches anyObject];

// If the touch was in the placardView, bounce it back to the center
if ([touch view] == placardView) {
// Disable user interaction so subsequent touches don’t interfere with animation
self.userInteractionEnabled = NO;
[self animatePlacardViewToCenter];
return;
}
}

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

placardView.center = self.center;
placardView.transform = CGAffineTransformIdentity;
}
- (void)animateFirstTouchAtPoint:(CGPoint)touchPoint {

#define GROW_ANIMATION_DURATION_SECONDS 0.15

NSValue *touchPointValue = [[NSValue valueWithCGPoint:touchPoint] retain];
[UIView beginAnimations:nil context:touchPointValue];
[UIView setAnimationDuration:GROW_ANIMATION_DURATION_SECONDS];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(growAnimationDidStop:finished:context:)];
CGAffineTransform transform = CGAffineTransformMakeScale(1.2, 1.2);
placardView.transform = transform;
[UIView commitAnimations];
}

- (void)growAnimationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {

#define MOVE_ANIMATION_DURATION_SECONDS 0.15

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:MOVE_ANIMATION_DURATION_SECONDS];
placardView.transform = CGAffineTransformMakeScale(1.1, 1.1);
NSValue *touchPointValue = (NSValue *)context;
placardView.center = [touchPointValue CGPointValue];
[touchPointValue release];
[UIView commitAnimations];
}

#else
- (void)animateFirstTouchAtPoint:(CGPoint)touchPoint {

#define GROW_ANIMATION_DURATION_SECONDS 0.15
#define SHRINK_ANIMATION_DURATION_SECONDS 0.15

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:GROW_ANIMATION_DURATION_SECONDS];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(growAnimationDidStop:finished:context:)];
CGAffineTransform transform = CGAffineTransformMakeScale(1.2, 1.2);
placardView.transform = transform;
[UIView commitAnimations];

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:GROW_ANIMATION_DURATION_SECONDS + SHRINK_ANIMATION_DURATION_SECONDS];
placardView.center = touchPoint;
[UIView commitAnimations];
}

- (void)growAnimationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:SHRINK_ANIMATION_DURATION_SECONDS];
placardView.transform = CGAffineTransformMakeScale(1.1, 1.1);
[UIView commitAnimations];
}

#endif

- (void)animatePlacardViewToCenter {

// Bounces the placard back to the center

CALayer *welcomeLayer = placardView.layer;

// Create a keyframe animation to follow a path back to the center
CAKeyframeAnimation *bounceAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
bounceAnimation.removedOnCompletion = NO;

CGFloat animationDuration = 1.5;

// Create the path for the bounces
CGMutablePathRef thePath = CGPathCreateMutable();

CGFloat midX = self.center.x;
CGFloat midY = self.center.y;
CGFloat originalOffsetX = placardView.center.x - midX;
CGFloat originalOffsetY = placardView.center.y - midY;
CGFloat offsetDivider = 4.0;

BOOL stopBouncing = NO;

// Start the path at the placard’s current location
CGPathMoveToPoint(thePath, NULL, placardView.center.x, placardView.center.y);
CGPathAddLineToPoint(thePath, NULL, midX, midY);

// Add to the bounce path in decreasing excursions from the center
while (stopBouncing != YES) {
CGPathAddLineToPoint(thePath, NULL, midX + originalOffsetX/offsetDivider, midY + originalOffsetY/offsetDivider);
CGPathAddLineToPoint(thePath, NULL, midX, midY);

offsetDivider += 4;
animationDuration += 1/offsetDivider;
if ((abs(originalOffsetX/offsetDivider) &lt; 6) &amp;&amp; (abs(originalOffsetY/offsetDivider) &lt; 6)) {
stopBouncing = YES;
}
}

bounceAnimation.path = thePath;
bounceAnimation.duration = animationDuration;
CGPathRelease(thePath);

// Create a basic animation to restore the size of the placard
CABasicAnimation *transformAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
transformAnimation.removedOnCompletion = YES;
transformAnimation.duration = animationDuration;
transformAnimation.toValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];

// Create an animation group to combine the keyframe and basic animations
CAAnimationGroup *theGroup = [CAAnimationGroup animation];

// Set self as the delegate to allow for a callback to reenable user interaction
theGroup.delegate = self;
theGroup.duration = animationDuration;
theGroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];

theGroup.animations = [NSArray arrayWithObjects:bounceAnimation, transformAnimation, nil];

// Add the animation group to the layer
[welcomeLayer addAnimation:theGroup forKey:@"animatePlacardViewToCenter"];

// Set the placard view’s center and transformation to the original values in preparation for the end of the animation
placardView.center = self.center;
placardView.transform = CGAffineTransformIdentity;
}

- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag {
//Animation delegate method called when the animation’s finished:
// restore the transform and reenable user interaction
placardView.transform = CGAffineTransformIdentity;
self.userInteractionEnabled = YES;
}

Step 7: Now compile and see the output on the simulator.

WP Greet Box icon
Hello there! If you are new here, you might want to subscribe to the RSS feed for updates on this topic, and free programming tips and tricks and source code            snippets.

1 Response » to “MoveImage in Iphone”

Leave a Reply

Security Code:

learn iphone programming

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Our Mobile Training Courses

EDUmobile.ORG offers the following 4 Mobile Training Courses. Our iPhone Training Course is very popular, with over 200 developers in training.

learn iphone programming
© 2010 EDUmobile.ORG