Reputation: 25697
I have an app with images displayed in it. I have various images at different sizes displayed in my UIImageView
.
What I want to do is set a size for the image view - call it 100x100.
Is there a way to do this in a normal UIImageView? Do I need to do some magic somewhere?
Upvotes: 1
Views: 4377
Reputation: 25697
This answer helped me in the end. It had this code:
- (CGSize) aspectScaledImageSizeForImageView:(UIImageView *)iv image:(UIImage *)im {
float x,y;
float a,b;
x = iv.frame.size.width;
y = iv.frame.size.height;
a = im.size.width;
b = im.size.height;
if ( x == a && y == b ) { // image fits exactly, no scaling required
// return iv.frame.size;
}
else if ( x > a && y > b ) { // image fits completely within the imageview frame
if ( x-a > y-b ) { // image height is limiting factor, scale by height
a = y/b * a;
b = y;
} else {
b = x/a * b; // image width is limiting factor, scale by width
a = x;
}
}
else if ( x < a && y < b ) { // image is wider and taller than image view
if ( a - x > b - y ) { // height is limiting factor, scale by height
a = y/b * a;
b = y;
} else { // width is limiting factor, scale by width
b = x/a * b;
a = x;
}
}
else if ( x < a && y > b ) { // image is wider than view, scale by width
b = x/a * b;
a = x;
}
else if ( x > a && y < b ) { // image is taller than view, scale by height
a = y/b * a;
b = y;
}
else if ( x == a ) {
a = y/b * a;
b = y;
} else if ( y == b ) {
b = x/a * b;
a = x;
}
return CGSizeMake(a,b);
}
Upvotes: 1
Reputation: 104092
You can do this with a normal UIImage view. For the larger image, you want to set the image view's Mode in IB to Aspect Fit or Scale To Fill (depending on whether you want the aspect ratio to stay the same or not), and for the smaller image, set it to Center.
You can do the same thing in code by using the contentMode property of the imageView.
Upvotes: 2
Reputation: 41672
If the image is smaller then add the UIImageView to a new transparent view and center it in that view. If larger then decide how you want the view resized (look at the resize option in UIView), and use just that UIImageView.
Upvotes: 1