我想更改我的 UIImageView 高度/宽度以匹配我从相册中选择的图像,我在这里找到了一个片段。
-(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, 0, width, imagev.frame.size.height);
return CGRectMake(topLeftX, 0, width, 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, topLeftY, imagev.frame.size.width, 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];
}