簡體   English   中英

如何為所需的UIImage Crop iOS 8.4確定正確的CGFloat值

[英]How to determine correct CGFloat values for desired UIImage Crop iOS 8.4

目前,我正在使用以下方法裁剪從UIImagePickerController收到的UIImage

- (UIImage *)imageByCroppingImage:(UIImage *)image toSize:(CGSize)size
{
    double refWidth = CGImageGetWidth(image.CGImage);
    double refHeight = CGImageGetHeight(image.CGImage);

    double x = (refWidth - size.width) / 2.0;
    double y = (refHeight - size.height) / 2.0;

    CGRect cropRect = CGRectMake(x, y, size.height, size.width);
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);

    UIImage *cropped = [UIImage imageWithCGImage:imageRef scale:0.0 orientation:image.imageOrientation];
    CGImageRelease(imageRef);

    return cropped;
}

我正在嘗試以完全精確的精度在UIImagePickerControllerOriginalImage的中間捕獲方形照片。 為此,我在我的方法中使用上面的方法,當用戶從UIImagePickerController單擊“使用照片”時觸發該方法:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    picker.cameraFlashMode = UIImagePickerControllerCameraFlashModeOff;

    picker.allowsEditing = YES;
    UIImage *img = [info objectForKey:UIImagePickerControllerOriginalImage];
    UIImageWriteToSavedPhotosAlbum(img,nil,nil,nil);

    CGRect cropRect = CGRectMake(264, 0, 2448, 3000);
    CGSize sizeOfCrop = CGSizeMake(2550, 2500);  //<---NEED HELP, float sizes for photo of size 320x320(640x640)?

    UIImage *croppedImage = [self imageByCroppingImage:img toSize:sizeOfCrop]; //cropping the UIImage  

    UINavigationController *postControl = [self.storyboard instantiateViewControllerWithIdentifier:@"postControl"];
    RGPostViewController *postView = (RGPostViewController *)postControl.topViewController;

    [postView storeImage:imageToPass]; //store image in destinationViewController
    [self.presentedViewController presentViewController:postControl animated:NO completion:nil];
}

此代碼可以正常工作,並且確實可以捕獲原始圖像的中心。 問題是我不知道提供CGSize sizeOfCrop的正確CGFloat值,我在其中添加了注釋“ < CGSize sizeOfCrop HELP”。

我必須將哪些CGFloat值傳遞給CGSizeMake才能從中間獲取精確的完美正方形圖片? 一幅非常適合UIImageView的圖片,其CGRect的寬度和高度為320x320。

您可以將我的評論同時應用於高度和寬度。 由於您要處理一個恆定的中心點,因此只需要寬度和高度之間的增量,然后除以2即可得到原點。 而且,由於您已經知道原始大小和目標(裁剪)大小,因此只需將原始圖像繪制到裁剪區域即可:

CGFloat cropWidth = 320;
CGFloat cropHeight = 320;

CGSize cropSize = CGSizeMake(cropWidth, cropHeight);
UIGraphicsBeginImageContext(cropSize);

CGFloat cropX = (originalImage.size.width / 2) - (cropWidth / 2);
CGFloat cropY = (originalImage.size.height / 2) - (cropHeight / 2);
CGSize cropRect = CGSizeMake(cropX, cropY, cropWidth, cropHeight);

[originalImage drawInRect:cropRect];

UIImage* croppedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

警告:未經測試。 如果無法正確居中,則應該能夠使用此答案中的原則來使圖像居中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM