user377419
user377419

Reputation: 5009

Cocoa Touch - Moving an UIImageView around on screen

What's a simple way to let users drag an UIImageView around to position it in the place of their choice. It's for a photography app.

Thanks!

Upvotes: 3

Views: 1417

Answers (1)

tadejsv
tadejsv

Reputation: 2092

First, make a container view that would take care of touch events. Then, you need a UIIMageView subclass that will make sure, that when you set a center of the object, it doesn't go off-the-screen.

I made a class like that some time ago, here's the code (it can also be animatable).

.h

#import <UIKit/UIKit.h>

@interface ObjectView : UIImageView 
{
}

-(void) setCenter: (CGPoint) center inBounds: (CGRect) bounds withAnimation: (BOOL) animate;

@end

.m

#import "ObjectView.h"

@implementation ObjectView

#define MOVE_TO_CENTER_DURATION 0.1
-(void) setCenter: (CGPoint) center inBounds: (CGRect) bounds withAnimation: (BOOL) animate
{
    CGRect frame = self.frame;

    if(center.x + frame.size.width/2 > bounds.origin.x + bounds.size.width) 
        center.x -= ((center.x + frame.size.width/2) - (bounds.origin.x + bounds.size.width));
    else if(center.x - frame.size.width/2 < bounds.origin.x) 
        center.x += bounds.origin.x - (center.x - frame.size.width/2);

    if(center.y + frame.size.height/2 > bounds.origin.y + bounds.size.height) 
        center.y -= (center.y + frame.size.height/2) - (bounds.origin.y + bounds.size.height);
    else if(center.y - frame.size.height/2 < bounds.origin.y) 
        center.y += bounds.origin.y - (center.y - frame.size.height/2);

    if(animate) {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration: MOVE_TO_CENTER_DURATION];
    }

    self.center = center;

    if(animate)
        [UIView commitAnimations];

} 

@end

Hope it helps a bit!

Upvotes: 2

Related Questions