我尝试使用iPhone相机拍摄照片并将其保存到文档文件夹和相册中,然后将此图像加载到另一个场景中。这是我的代码:
用于图像保存(在场景A中):
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.ImageView.image = chosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
NSString *mediaType = info[UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
NSString *fileName = [NSString stringWithFormat:@"%@.png", self.patientMRN];
NSURL *urlSave = [[self getDocumentsPathURL] URLByAppendingPathComponent:fileName];
[UIImagePNGRepresentation(chosenImage) writeToFile:urlSave.path atomically:YES];
UIImageWriteToSavedPhotosAlbum(chosenImage, nil, nil, nil);
}
}
对于图像加载(在场景B中):
-(void)loadDefaultImage
{
NSString *fileName = [NSString stringWithFormat:@"%@.png", self.patientMRN];
NSURL *urlImage = [[self getDocumentsPathURL] URLByAppendingPathComponent:fileName];
if ([[NSFileManager defaultManager] fileExistsAtPath:urlImage.path]) {
NSData *dataFile = [[NSFileManager defaultManager] contentsAtPath:urlImage.path];
UIImage *image = [[UIImage alloc] initWithData:dataFile];
self.imageView.contentMode = UIViewContentModeScaleAspectFill;
self.imageView.autoresizingMask =
( UIViewAutoresizingFlexibleBottomMargin
| UIViewAutoresizingFlexibleHeight
| UIViewAutoresizingFlexibleLeftMargin
| UIViewAutoresizingFlexibleRightMargin
| UIViewAutoresizingFlexibleTopMargin
| UIViewAutoresizingFlexibleWidth );
self.imageView.image = image;
}
else {
NSLog(@"Image not found");
}
}
现在我有两个问题。
在场景A中,我有一个UIImageView,我为其设置了高度和宽度约束。在UIImageView下面,我有两个按钮,一个用于拍照,另一个用于返回。拍摄照片并选择使用照片后,它将返回场景A并在UIImageView中显示捕获的图像。但是,显示的图像太大了,它下方的两个按钮部分重叠,好像我设置的约束根本不起作用。为什么会这样?
在场景B中,我有一个较小的UIImageView用于显示我之前拍摄的照片。但是,只有部分原始图像显示在场景B的imageView中。我尝试将contentMode设置为UIViewContentModeScaleAspectFill并设置autoresizingMask,但仍然无法正常工作。它出了什么问题?
编辑:
问题解决了!在我将UIImageview拖到故事板后,我只是调整它以适应屏幕,但忘了添加高度和宽度限制。现在我添加约束,图像按预期显示。谢谢你们。
答案 0 :(得分:0)
您是否尝试过不仅设置contentMode
属性,还设置clipsToBounds
?
self.imageView.contentMode = UIViewContentModeScaleAspectFill;
self.imageView.clipsToBounds = YES;