我想改变我的UI
ImageView高度/宽度,以匹配我从相册中选择的图像,我在这里找到一个代码片段.
-(CGRect)frameForImage:(UIImage *)imgs inImageViewAspectFit:(UIImageView *)imagev { float imageRatio = imgs.size.width / imgs.size.height; float viewRatio = imagev.frame.size.width / imagev.frame.size.height; if(imageRatio < viewRatio) { float scale = imagev.frame.size.height / imgs.size.height; float width = scale * imgs.size.width; float topLeftX = (imagev.frame.size.width - width) * 0.5; NSLog(@"image after aspect fit: width=%f",width); imagev.frame = CGRectMake(topLeftX,width,imagev.frame.size.height); return CGRectMake(topLeftX,imagev.frame.size.height); } else { float scale = imagev.frame.size.width / imgs.size.width; float height = scale * imgs.size.height; float topLeftY = (imagev.frame.size.height - height) * 0.5; NSLog(@"image after aspect fit: height=%f",height); imagev.frame = CGRectMake(0,topLeftY,imagev.frame.size.width,height); return CGRectMake(0,height); } }
问题是当我从一个按钮调用它时,它会改变UIImageView的高度/宽度
- (IBAction)changeSize:(id)sender { [self frameForImage:image inImageViewAspectFit:self.imageView]; }
但是,我想要这样做,一旦我从相册中选择一个图像,这是我如何设置.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { image = [info objectForKey:UIImagePickerControllerOriginalImage]; [self.imageView setImage:image]; [self frameForImage:image inImageViewAspectFit:self.imageView]; [self dismissViewControllerAnimated:YES completion:NULL]; }
解决方法
自动布局解决方案
自从确定您在项目中使用自动布局之后,我已经做了一个演示程序,向您展示如何更改图像视图的图像并调整高度.自动布局将自动为您做这件事,但抓住的是您将要使用的照片来自用户画廊,因此可能会非常大.
所以看看应用程序:https://bitbucket.org/danielphillips/auto-layout-imageview
诀窍在于创建图像视图高度的NSLayoutConstraint的引用.当您更改图像时,需要将固定宽度调整到正确的高度.
您的其他解决方案可能是在您的图像视图中设置contentMode,通过使用UIViewContentModeScaleAspectFit,您的图像将始终以完整的方式显示,但将被锁定到图像视图的边界,这可以根据您拥有的自动布局约束进行更改.
初步答复
看起来你真的很复杂,除非我错过了一些东西.
当您从图像选择器获取新图像时,您只需要根据UIImage大小更改图像视图的框架.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { image = [info objectForKey:UIImagePickerControllerOriginalImage]; [self.imageView setImage:image]; self.imageView.frame = CGRectMake(self.imageView.frame.origin.x self.imageView.frame.origin.y image.size.width image.size.height); [self dismissViewControllerAnimated:YES completion:NULL]; }
当然,这可能是非常大的(它使用的原始图像可能非常大).
所以让我们将宽度锁定到280点…这样我们可以在纵向模式下始终在屏幕上显示完整的图像.
所以假设你的图像大小是1000×800,我们的图像视图也许是280×100.我们可以计算保持图像视图宽度的图像视图的正确高度,如下所示:
CGSize imageSize = CGSizeMake(1000.0,800.0); CGSize imageViewSize = CGSizeMake(280.0,100.0); CGFloat correctImageViewHeight = (imageViewSize.width / imageSize.width) * imageSize.height; self.imageView.frame = CGRectMake( self.imageView.frame.origin.x,self.imageView.frame.origin.x,CGRectGetWidth(self.imageView.bounds),correctImageViewHeight);