1

I am developing an app that will show flags for countries some places, but after looking at flags I realized that the flags format was different for almost every country. Therefor I would like the height of the image view to automatically adjust it self to the width i set. Example: Standard width for all flags: 100 px USA : Height: 50px UK: Height 56 px Russia: Height 34px

I have no idea how to solve this, thanks for help! The best would be if this could be done automatically - without me needing to create example arrays or something for every flag to adjust size.

Connor Pearson
  • 63,902
  • 28
  • 145
  • 142
ThomasGulli
  • 604
  • 1
  • 7
  • 20

2 Answers2

2

This is a ratio problem. Suppose your English flag is 120x80px. You want it to be 100px wide. How tall will it be? You have to scale the width and height by the same ratio.

First of all, calculate the ratio between the desired width of the flag and its actual width:

CGFloat ratio = 100.0f / 120.0f;

That gives us a ratio of 0.83. Now we can calculate the display height by multiplying the actual height by the ratio:

CGFloat height = 80.0f * 0.83;

The display height is 66.4px.


Here's the neat thing: UIImageView does this for you. If you specify the width of the image view and set its content mode to UIViewContentModeScaleAspectFit it does the hard work automatically.

See this question:

How to scale a UIImageView proportionally?

Community
  • 1
  • 1
Ant
  • 4,890
  • 1
  • 31
  • 42
1

You could set the size of the image view from the size of the image as follows:

UIImage* flagImage = [UIImage imageNamed:"flagimage.png"];
CGRect flagImageRect = flagImageView.frame;
flagImageRect.size = flagImage.size;
flagImageView.frame = flagImageRect;
flagImageView.image = flagImage;

I guess you would do the above in a loop where you are setting the flag images for all your image views. You could also take the opportunity to scale your images (if desired).

Ron
  • 1,249
  • 9
  • 20