使用相机拍摄的照片在 UIimageView 中无法调整大小



我的代码

- (IBAction)takePhoto:(UIButton *)sender {
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
    UIImagePickerController *picker = [UIImagePickerController new];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:picker animated:YES completion:nil];
}else{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ERROR!" message:@"Device has no camera!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}
}

和代表

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.userImage.image = chosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:NULL];
}

嗯,这非常简单和基本。我的问题是,将我的图像分配给我拥有的 UIImageView(具有固定/固定的宽度和高度)而不是将自身大小调整为 uiimageview 的大小,它会延伸到我的整个视图中,更多地作为背景将图像放置在应有的位置。同样,我的uiimageview的宽度和高度已被固定。有人可以帮忙吗?谢谢

UIImageViewcontentMode应该是 UIViewContentModeScaleAspectFit ,而不是看起来UIViewContentModeCenter

如果您需要即时更改内容模式,只需添加以下行:

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
    self.userImage.image = chosenImage;
    // Add this line
    self.userImage.contentMode = UIViewContentModeScaleAspectFit;
    [picker dismissViewControllerAnimated:YES completion:NULL];
}

最新更新