使用从 this post 中的 Frank Schmitt 略微修改的方法,您可以添加一个方法来计算显示缩放到纵横比的图像所需的帧:
- (CGRect)getFrameSizeForImage:(UIImage *)image inImageView:(UIImageView *)imageView {
float hfactor = image.size.width / imageView.frame.size.width;
float vfactor = image.size.height / imageView.frame.size.height;
float factor = fmax(hfactor, vfactor);
// Divide the size by the greater of the vertical or horizontal shrinkage factor
float newWidth = image.size.width / factor;
float newHeight = image.size.height / factor;
// Then figure out if you need to offset it to center vertically or horizontally
float leftOffset = (imageView.frame.size.width - newWidth) / 2;
float topOffset = (imageView.frame.size.height - newHeight) / 2;
return CGRectMake(leftOffset, topOffset, newWidth, newHeight);
}
您可以在设置 UIImageView 图像后调用它:
CGRect frame = [self getFrameSizeForImage:imageView.image inImageView:imageView];
最后,使用这个框架设置 UIImageView 的框架,偏移位置以适应宽度/高度的任何变化:
CGRect imageViewFrame = CGRectMake(imageView.frame.origin.x + frame.origin.x, imageView.frame.origin.y + frame.origin.y, frame.size.width, frame.size.height);
imageView.frame = imageViewFrame;