Eric Brotto
Eric Brotto

Reputation: 54251

Animating the cropping of UIView/ UIImageView

I have this chunk of code which is placed in accelerometer: didAccelerate which changes the cropping of an image. Basically as you tilt an iPad an image gets truncated (not resized) which is exactly the effect I'm looking for. Note: self.xPos is effected by the position of accelerometer.x.

UIImage *originalStringImage = [UIImage imageNamed:@"string.png"];
CGImageRef imageRef = CGImageCreateWithImageInRect([originalStringImage CGImage], CGRectMake(0.0f,0.0f, self.xPos+50.0f, 26.0f));
[self.stringImageView setImage:[UIImage imageWithCGImage:imageRef]];
self.stringImageView.frame = CGRectMake(10.0f, self.stringYPos, self.xPos+50.0f, 26.0f);

Now I would like to do the exact same thing, although as a UIView animation. Something between these UIView animation parameters:

UIImageView *pageStringImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10.0f, placeString, 0.0f, 42.0f)];

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDelay:2.0];
[UIView setAnimationDuration:3.0];
pageStringImageView.frame = CGRectMake(10.0f, placeString, 900.0f, 42.0f);
UIImage *originalStringImage = [UIImage imageNamed:@"string.png"];
CGImageRef imageRef = CGImageCreateWithImageInRect([originalStringImage CGImage], CGRectMake(10.0f,placeString, pageStringImageView.frame.origin.x, 42.0f));
[pageStringImageView setImage:[UIImage imageWithCGImage:imageRef]];
[UIView commitAnimations]; 

But the above doesn't work it all. In fact it doesn't even show the image. I believe the main difficulty here is changing the size of the image dynamically while the UIView animation is running.

Any suggestions or questions?

Upvotes: 0

Views: 2301

Answers (1)

lxt
lxt

Reputation: 31304

This should be fairly simple to do if you use the scaling properties of your UIImageView (the .contentMode property).

Views - including image views - can display there content in a number of ways. The default for an image view is to scale the content, so when you change the frame/bounds of the image it shrinks / expands as appropriate.

So if you were to use a standard UIView animation block to adjust the frame of a UIImageView it would animate the image scaling or shrinking. But if you change the image view's .contentMode property if you change the frame you can have it crop instead.

For example, UIViewContentModeLeft will align the content with the left hand side of the view, so if you adjust the width of the view it will be 'cropped' from the right side. Check the UIView documentation to see all the values you can have for contentMode. So basically, just animate your view's frame changing, but set the contentMode appropriately to give you the desired cropping effect. You may need to make sure your view is set to clip to bounds, although I have a feeling image views do this by default.

Upvotes: 5

Related Questions