UIImageView 方面适合高度

UIImageView aspect fit to height

我需要根据高度设置 UIImageView 大小 aspectfit 。

意味着我的要求是我的图像高度应该是固定的,但图像的宽度应该根据高度改变我知道在 UIViewContentModeScaleAspectFit 中它会自动获取宽度和高度但是如果我需要固定高度和动态宽度怎么办喜欢根据身高的aspectfit。

UIImage *originalImage = [UIImage imageNamed:@"image.png"];
double width = originalImage.size.width;
double height = originalImage.size.height;
double apect = width/height;

double nWidth = 320.f/ apect;
self.img.frame = CGRectMake(0, 0, nWidth, 320.f);
self.img.center = self.view.center;
self.img.image = originalImage;
-(CGSize)resizeImage:(CGSize)imageSize toTargetedHeight:(float)height {

 NSLog(@"actualImageSize : %@", NSStringFromCGSize(imageSize));

 float scaleFactor = height / imageSize.height;
 float newHeight = imageSize.height * scaleFactor;
 float newWidth = imageSize.width  * scaleFactor;

 CGSize newSize = CGSizeMake(newWidth, newHeight);

 NSLog(@"convertedImageSize : %@", NSStringFromCGSize(newSize));
 return newSize;

}

这将创建具有特定高度的图像,同时保持其纵横比。