Scaling Views

In this tutorial we will scale an imageview up and downwards using a slider. To scale an image we will use a Affine Transformation technique.

Open Xcode and create a new Single View Application. For product name, use ScalingViewsDemo and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices, and that the Use Storyboards checkbox is deselected and Use Automatic Reference Counting checkbox is selected.

First, Let's create our User Interface. Go to ViewController.xib. Drag a slider and a imageView to the main View. The main View should look like this.

In ViewController.m in the interface section declare the following properties.

@interface ViewController ()

@property (nonatomic, strong) IBOutlet UISLider *scaleSlider;
@property (nonatomic, strong) IBOutlet UIImageview *scaleView;

- (IBAction)scaleImage(id) sender;


Go back to ViewController.xib. Select the Assistant Editor. On the right side select ViewController.m. Ctrl-click and drag from the UISlider to the scaleSlider property in ViewController.m. Next, Ctrl-click and drag from the imageView to the scaleView property in ViewController.m. Also, Ctrl-click and drag from the UISlider to the scaleImage IBAction method.

In ViewController.m, change the viewDidLoad method to

- (void)viewDidLoad 
[super viewDidLoad];

//set slider values
self.scaleSlider.minimumValue = 0.5;
self.scaleSlider.maximumValue = 1.5;
self.scaleSlider.value = 1.0;

// load image
UIImage *image = [UIImage imageNamed:@"star.png"];
self.scaleView.image = image;

We set the min and max and starting values of our slider and load a image. Next, implement our IBAction scaleImage method.

- (IBAction)scaleImage:(UISlider *)sender 
self.scaleView.transform = CGAffineTransformMakeScale(sender.value, sender.value);

With the CGAFFineTransformMakeScale function, we will scale our image according to the slider's value. Build and Run and move the slider, you should see the image scale.

You can download the source code of the ShakeGestureDemo at the ioscreator repository on github.