Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CGAffineTransform and scaling to center of the image

I started studying objective-c using the iPhone and iPad apps for Absolute Beginners by Rory Lewis book but i got stuck on the 5th chapter.

I want to make a button that shrinks an image.
My problem is, that after I wrote all the code, the image shrinks to the point (0, 0) of the UIImageView (the top left), while in the video the image shrinks to its center. I've done some research and found out that CGAffineTransform uses the center of the object to make translations, rotations etc.

So why does it not work in my case?

I have the latest Xcode version and haven't done anything strange. I hope I've been clear. Sorry for my English.

EDIT Sorry for the code, but i wrote the question from my phone. Anyway the incriminated part goes something like this

- (IBAction)shrink:(id)sender {

if(hasShrink == NO){
    [shrinkButton setTitle:@"Grow" forState:UIControlStateNormal];
}
else if(hasShrink == YES){
    [shrinkButton setTitle:@"Shrink" forState:UIControlStateNormal];
}
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:1.0];
        myIcon.transform = CGAffineTransformMakeScale(.25, .25);
        hasShrink = YES;
        [UIView commitAnimations];

}

All the animations are correctly written and the app does work, it just shrinks to the top left. Why is the point not set to the center of the UIImageView by default like it should be?

EDIT: I figured out it was a problem caused by AutoLayout. Once disabled everything went smooth ;)

like image 848
halfblood17 Avatar asked Dec 04 '12 15:12

halfblood17


2 Answers

If you are transforming a view mangled managed by auto-layout, you may experience some strange side-effects. See this answer for more details.

The solution I ended up employing was to encapsulate the view I wanted to transform inside another view of exactly the same size. The outer view had the appropriate layout constraints applied to it while the inner view was simply centered in its container. Applying a CGAffineTransform scale transform to the inner view now centers properly.

like image 83
devios1 Avatar answered Oct 16 '22 18:10

devios1


Old question... but just in case others come looking:

The CGAffineTransform acts (rotates, scales) around an anchorPoint.

If you are sizing to 0, 0 then your anchor point is set to 0, 0. If you want it to size to a different point, such as the center of the image, you need to change the anchor point.

The anchor is part of a layer

So if you have a UIImageView called imageview, you would make a call like this to set the anchor to the center of imageview:

[imageview.layer setAnchorPoint:CGPointMake(0.5, 0.5)];
like image 8
HalR Avatar answered Oct 16 '22 18:10

HalR