5 Replies - 986 Views - Last Post: 15 January 2016 - 09:46 PM

#1 AlfredoMayFire  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 23
  • Joined: 10-February 14

Need help rotating a UIImageView.

Posted 07 January 2016 - 02:57 PM

Hello all! So I'm completely new to using Objective-C and programming IOS apps. I've so far manage to assemble a sort of sandbox project here. So basically at this point I'm looking to add a button(of any type but preferably a slider) that will allow me to rotate one of the images. Now I'm no stranger to programming but the help I've found online is hard to understand mostly because I'm new to this but secondly because I mostly learn from a direct example. Since the help I've found is mostly abstract I haven't been able to understand. I really mostly need help with the following things.
1) Implementing any type of rotating function with my image. For example do i pass the image as a parameter to a given function?
2) Implementing as a button. I want the button to be directly affect the image. In the case of the slider the object would rotate as the slider increases in value, up to 360.
Any beginning nudges would be greatly appreciated.
viewcontroller.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    IBOutlet UIImageView * image;
    IBOutlet  UIImageView * collisionImage;
    IBOutlet UIImageView * object;
}

- (void)ifCollided;

@end

 


viewcontroller.m
#import "ViewController.h"


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    //image.image = [UIImage imageNamed:@"blackcar.jpg"];
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor clearColor];
    // Do any additional setup after loading the view, typically from a nib.
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches]anyObject];
    //CGPoint location = [touch locationInView:touch.view];
    //[[touch view] setCenter:CGPointMake(x, y)];
    image.center = [touch locationInView:self.view];
    [self ifCollided];
}

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self touchesBegan:touches withEvent:event];
    UITouch *myTouch = [[event allTouches] anyObject];
    object.center = [myTouch locationInView:self.view];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void) checkCollision
{
    if(CGRectIntersectsRect(object.frame, object.frame))
    {
        //[object setHidden:YES];
        //NSLog(@"!!!!!!!Collision");
    }
}

-(void) ifCollided
{
    if (CGRectIntersectsRect(image.frame, collisionImage.frame))
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Collision Detected" message:@"Accident Reported" delegate:self cancelButtonTitle:@"Reset" otherButtonTitles:@"ok", nil];
        [alert show];
        //[alert release];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 0)
    {
        image.center = CGPointMake(159, 750);
    }
}

@end



app delegate.m
#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [self.window setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"2000px-Street_intersection_diagram"]]];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "example.PhotoCollider" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"PhotoCollider" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"PhotoCollider.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonerrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end



app delegate.h
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;


@end



Is This A Good Question/Topic? 0
  • +

Replies To: Need help rotating a UIImageView.

#2 AlfredoMayFire  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 23
  • Joined: 10-February 14

Re: Need help rotating a UIImageView.

Posted 07 January 2016 - 03:37 PM

Actually I've managed to add the slider and a text Label that shows the value of the slider. Maybe there might be a way to grab that value to rotate the image?
Was This Post Helpful? 0
  • +
  • -

#3 AlfredoMayFire  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 23
  • Joined: 10-February 14

Re: Need help rotating a UIImageView.

Posted 08 January 2016 - 12:30 PM

Edit: I've managed to make a slider and text label that updates with the value from the slider.
viewcontroller.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    IBOutlet UIImageView * image;
    IBOutlet  UIImageView * collisionImage;
    IBOutlet UIImageView * object;
}
@property (weak, nonatomic) IBOutlet UILabel *MyLabel;
- (void)ifCollided;

@end


viewcontroller.m
#import "ViewController.h"
#import <math.h>


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    //image.image = [UIImage imageNamed:@"blackcar.jpg"];
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor clearColor];
    // Do any additional setup after loading the view, typically from a nib.
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches]anyObject];
    //CGPoint location = [touch locationInView:touch.view];
    //[[touch view] setCenter:CGPointMake(x, y)];
    image.center = [touch locationInView:self.view];
    [self ifCollided];
}

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self touchesBegan:touches withEvent:event];
    UITouch *myTouch = [[event allTouches] anyObject];
    object.center = [myTouch locationInView:self.view];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void) checkCollision
{
    if(CGRectIntersectsRect(object.frame, object.frame))
    {
        //[object setHidden:YES];
        //NSLog(@"!!!!!!!Collision");
    }
}

-(void) ifCollided
{
    if (CGRectIntersectsRect(image.frame, collisionImage.frame))
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Collision Detected" message:@"Accident Reported" delegate:self cancelButtonTitle:@"Reset" otherButtonTitles:@"ok", nil];
        [alert show];
        //[alert release];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 0)
    {
        image.center = CGPointMake(159, 750);
    }
}

- (IBAction)sliderUpdate:(id)sender
{
    UISlider* slider = (UISlider *)sender;
    NSString *newValue;
    newValue = [NSString stringWithFormat:@"%f", slider.value];
    self.MyLabel.text = newValue;
}

@end





Now what I want is to grab the value from the slider and use
imageView.transform = CGAffineTransformMakeRotation(radianRotation);
function to rotate the image. Except what i want is that automatically when the slider moves for the image to rotate along with it. Hope this helps simplify the problem and get me some help.
Was This Post Helpful? 0
  • +
  • -

#4 trixt.er  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 53
  • View blog
  • Posts: 431
  • Joined: 28-September 08

Re: Need help rotating a UIImageView.

Posted 08 January 2016 - 01:39 PM

You may not like this answer but I would strongly encourage using Swift 2 and running on the latest XCode for iOS9. The "Apple" way is to use the latest and greatest. Swift is the future and Objective-C may soon (next few years) be extinct. Swift is now open source:

https://github.com/apple/swift
Was This Post Helpful? 0
  • +
  • -

#5 AlfredoMayFire  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 23
  • Joined: 10-February 14

Re: Need help rotating a UIImageView.

Posted 08 January 2016 - 02:09 PM

Well I would consider this if I could mix the languages together. This mini pet project is supposed to be integrated into a bigger project which is already majorly done in Objective-C. Plus I wouldn't start from scratch because I've put in some legwork here. Maybe any other suggestions/help.
Was This Post Helpful? 0
  • +
  • -

#6 AlfredoMayFire  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 23
  • Joined: 10-February 14

Re: Need help rotating a UIImageView.

Posted 15 January 2016 - 09:46 PM

Alright I found a solution a while back and am going to post the code cause I feel it could be of help to future people.
in the viewcontroller.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    IBOutlet UIImageView * image;
    IBOutlet  UIImageView * collisionImage;
    IBOutlet UIImageView * object;
    float angle_rotated;
    float angle_rotated2;
}
@property (weak, nonatomic) IBOutlet UILabel *MyLabel;
@property (nonatomic, retain) IBOutlet UIButton *button;
@property (weak, nonatomic) IBOutlet UILabel *MyLabel2;
@property (nonatomic, retain) IBOutlet UIButton *button2;
- (void)ifCollided;

@end




and in the viewcontroller.m
//
//  ViewController.m
//  PhotoCollider
//
//  Created by ricardo flores on 12/24/15. Collaboration with Alfredo Pomales III.
//  Copyright  2015 ricardo flores. All rights reserved.
//

#import "ViewController.h"
#import <math.h>


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor clearColor];
    [_button addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_button];
//////////////////////////////////////////////
    [_button2 addTarget:self action:@selector(btnClicked2:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_button];
    // Do any additional setup after loading the view, typically from a nib.
    angle_rotated = 0;
    angle_rotated2 = 0;
    
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches]anyObject];
    CGPoint location = [touch locationInView:self.view];
    [self ifCollided];
    if([touch view]== image)
    {
        image.center = location;
    }
    else if([touch view] == collisionImage)
    {
        collisionImage.center = location;
    }
}
-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self touchesBegan:touches withEvent:event];
    UITouch *myTouch = [[event allTouches] anyObject];
    object.center = [myTouch locationInView:self.view];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void) ifCollided
{
    if (CGRectIntersectsRect(image.frame, collisionImage.frame))
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Collision Detected" message:@"Accident Reported" delegate:self cancelButtonTitle:@"Reset" otherButtonTitles:@"ok", nil];
        [alert show];
        //[alert release];
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 0)
    {
        image.center = CGPointMake(159, 750);
        collisionImage.center = CGPointMake(159, 150);
        image.transform = CGAffineTransformMakeRotation(0);
       collisionImage.transform = CGAffineTransformMakeRotation(0);
    }
}
- (IBAction)sliderUpdate:(id)sender
{
    UISlider* slider = (UISlider *)sender;
    NSString *newValue;
    newValue = [NSString stringWithFormat:@"%f", slider.value];
    self.MyLabel.text = newValue;
}
- (IBAction)btnClicked:(id)sender
{
    angle_rotated += M_PI/6;
    image.transform = CGAffineTransformMakeRotation(angle_rotated);
}

- (IBAction)btnClicked2:(id)sender
{
    angle_rotated2 += M_PI/6;
   collisionImage.transform = CGAffineTransformMakeRotation(angle_rotated2);
}

@end




Essentially we use a button to cause the change the angle of view. Each time we add pi/6th of a rotation but this number can be toyed with to allow for more precise or less precise rotations.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1