我正在尝试创建一个带有方形图片的相机按钮,然后填充CollectionViewController单元格。现在,我在裁剪图片并将其输出到单元格时遇到了一些麻烦。在代码行中注释“将图像裁剪为正方形:我收到一条错误,说”图像“是未声明的标识符。如何裁剪图像并将其设置为单元格?
- (IBAction)cameraButtonClicked:(id)sender {
if (![UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypeCamera)]) {
UIAlertView *cameraAlertView = [[UIAlertView alloc] initWithTitle:@"Camera Not Available" message:@"There is no camera on this device which really defeats the purpose of this game. We suggest you get an iDevice with a camera." delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil];
[cameraAlertView show];
}else{
UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
if (ipc.sourceType == UIImagePickerControllerSourceTypeCamera) {
//Create camera overlay
CGRect f = ipc.view.bounds;
f.size.height -= ipc.navigationBar.bounds.size.height;
CGFloat barHeight = (f.size.height - f.size.width) / 2;
UIGraphicsBeginImageContext(f.size);
[[UIColor colorWithWhite:0 alpha:.5] set];
UIRectFillUsingBlendMode(CGRectMake(0, 0, f.size.width, barHeight), kCGBlendModeNormal);
UIRectFillUsingBlendMode(CGRectMake(0, f.size.height - barHeight, f.size.width, barHeight), kCGBlendModeNormal);
UIImage *overlayImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *overlayIV = [[UIImageView alloc] initWithFrame:f];
overlayIV.image = overlayImage;
[ipc.cameraOverlayView addSubview:overlayIV];
}
ipc.delegate = self;
[self presentViewController:ipc animated:YES completion:nil];
//Crop the image to a square
CGSize imageSize = image.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
if (width != height) {
CGFloat newDimension = MIN(width, height);
CGFloat widthOffset = (width - newDimension) / 2;
CGFloat heightOffset = (height - newDimension) / 2;
UIGraphicsBeginImageContextWithOptions(CGSizeMake(newDimension, newDimension), NO, 0.);
[image drawAtPoint:CGPointMake(-widthOffset, -heightOffset)
blendMode:kCGBlendModeCopy
alpha:1.];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
}
}
#pragma mark ImagePicker Delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self dismissViewControllerAnimated:YES completion:nil];
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
self.imageView.image = image;
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
答案 0 :(得分:0)
将您的“裁剪”编码移到此行下方:
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
in
didFinishPickingMediaWithInfo
您需要使用新裁剪的图像更新dataSource。然后,您可以在UICollectionView上调用reloadData
或insertItemsAtIndexPaths:
,使其反映新添加的图像。我会支持调用后一种方法,因为它比使用reloadData
重新加载整个集合更有效(当集合中有大量图像时)。
UICollectionView
引用为here。