My Blog List

Android FirstAid Coding

A Small Help From a Small Heart
Powered by Blogger.

A software professional, who still likes to code, likes to blog and loves gadgets.

Friday 23 May 2014

Calculating new width and height with maintaining aspect ratio of Image in iOS





Image original width = 100 and height = 150
Container width  = 200 and height = 200

x-ratio = Container width / Image original width = 200/100 = 2.0
y-ratio =  Container height / Image original height = 200/ 1501.33

Selected ratio = min (x-ratio, y-ratio) = 1.33

Final Image width = Image original width * Selected Ratio = 100 * 1.33 = 133
Final Image height = Image original height * Selected Ratio = 150 * 1.33 = 200

Final Image width x height = 133 x 200 (Original width x height of image was 100 x 150)

float leftOffset = (Container width - finalImageWidth) / 2;
float topOffset = (Container width - finalImageHeight) / 2;
[self.imageView setFrame:CGRectMake(leftOffset,topOffset, finalImageWidth, finalImageHeight)];
[self.imageView setImage:@"image name"];

self.imageView.contentMode = UIViewContentModeScaleAspectFit;