This answer最終幫了我。它有這樣的代碼:
- (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);
}
這是很多代碼,您可以這樣做:if(myImage.size> 200x300)myImageView.contentMode = UIViewContentModeScaleAspectFit; – 2013-04-29 12:23:56
您需要舍入或截斷a和b,以使它們都是整數。 – 2013-06-04 19:41:03
@DavidH它爲我的目的工作得很好,隨時做任何必要的更改。 – Undo 2013-06-04 19:43:01