Objective C - 设置 ImageView 宽度并保持纵横比
Objective C - Set ImageView Width and Maintain Aspect Ratio
我正在使用以下动画在视图上显示缩略图的全屏图像:
[UIView animateWithDuration:0.5 delay:0 options:0 animations:^{
[testImageView setFrame:CGRectMake(0, 0, testImage.size.width, testImage.size.height)];
}completion:^(BOOL finished){
}];
但是,如果是大图,则不会包含屏幕边界内的图像。
有什么方法可以将图片的宽度设置为屏幕的宽度,然后调整图片的高度,以保持适当的纵横比?
CGRect bounds = [UIScreen mainScreen].bounds;
[testImageView setFrame:bounds];
testImageView.contentMode = UIViewContentModeScaleAspectFit;
但是如果图像的比例不等于屏幕可能会有一些填充's.If您希望图像覆盖整个屏幕,然后将 contentMode 更改为 UIViewContentModeScaleAspectFill。
与上述方法类似,但有更多修改:
CGFloat verticalScale = image.height / bounds.height;
CGFloat horizontalScale = image.width / bounds.width;
CGFloat scale = max(verticalScale,horizontalScale);
CGFloat imageViewHeight = image.height / scale;
CGFloat imageViewWidth = image.width / scale;
CGRect imageViewFrame = CGRectMake(x: DESIRE_X, y: DESIRE_Y, width:imageViewWidth ,height:imageViewHeight)
imageView.frame = imageViewFrame;
imageView.contentMode = UIViewContentModeScaleAspectFill;
请尝试以下代码:
testImageView
=[[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y ,self.view.frame.size.width, self.view.frame.size.height
)]
我正在使用以下动画在视图上显示缩略图的全屏图像:
[UIView animateWithDuration:0.5 delay:0 options:0 animations:^{
[testImageView setFrame:CGRectMake(0, 0, testImage.size.width, testImage.size.height)];
}completion:^(BOOL finished){
}];
但是,如果是大图,则不会包含屏幕边界内的图像。
有什么方法可以将图片的宽度设置为屏幕的宽度,然后调整图片的高度,以保持适当的纵横比?
CGRect bounds = [UIScreen mainScreen].bounds;
[testImageView setFrame:bounds];
testImageView.contentMode = UIViewContentModeScaleAspectFit;
但是如果图像的比例不等于屏幕可能会有一些填充's.If您希望图像覆盖整个屏幕,然后将 contentMode 更改为 UIViewContentModeScaleAspectFill。
与上述方法类似,但有更多修改:
CGFloat verticalScale = image.height / bounds.height;
CGFloat horizontalScale = image.width / bounds.width;
CGFloat scale = max(verticalScale,horizontalScale);
CGFloat imageViewHeight = image.height / scale;
CGFloat imageViewWidth = image.width / scale;
CGRect imageViewFrame = CGRectMake(x: DESIRE_X, y: DESIRE_Y, width:imageViewWidth ,height:imageViewHeight)
imageView.frame = imageViewFrame;
imageView.contentMode = UIViewContentModeScaleAspectFill;
请尝试以下代码:
testImageView
=[[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y ,self.view.frame.size.width, self.view.frame.size.height
)]