要更改捕获的图像的大小,您需要UIImageView
在 IB 中设置查看模式以缩放以填充。然后当从库或相机中选择图像时,它会自动调整大小。您确实必须关闭自动布局,因为它不允许ImageView
调整大小。你的代码很好。无论如何,这里是示例应用程序代码,您可以构建以更好地理解它。
。H
#import <UIKit/UIKit.h>
@interface ImageTestViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (strong, nonatomic) IBOutlet UIImageView *imageView;
- (IBAction)takePhoto: (UIButton *)sender;
- (IBAction)selectPhoto:(UIButton *)sender;
@end
.m
#import "ImageTestController.h"
@interface ImageTestViewController ()
@end
@implementation ImageTestViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Error"
message:@"Device has no camera"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[myAlertView show];
}
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
- (IBAction)takePhoto:(UIButton *)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:NULL];
}
- (IBAction)selectPhoto:(UIButton *)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.imageView.image = chosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:NULL];
}
@end
在ImageTestController
Xib 或情节提要中的视图中,放置两个按钮,每个按钮一个,并在 IB 中创建必要的链接。然后放置 aUIImageView
以填充视图中您想要的任何大小。单击UIImageView
属性检查器的视图部分,将模式更改为缩放以填充。关闭自动布局。尝试将图像添加到您的模拟器只是为了测试它。确保图像是横向尺寸。构建并运行,当您从图像库中选择图像时,它会自动调整为正方形或您设置的任何其他大小UIImageView
。
我知道您知道上述大部分步骤,但我写这个答案不仅是为了帮助您摆脱您的问题,而且是为了其他可能有类似问题的人。希望它可以帮助你。