IOS / CGSize:如何裁剪图像以填充空间

时间:2015-05-12 23:50:16

标签: ios cgsize

我正在尝试按照提供调整图像大小的类别的教程。但是代码崩溃在以下几行:

CGSize mainImageSize = self.size;

断点处的调试器说:

size    CGSize  (width=142, height=142) 
mainImageSize   CGSize  (width=2.121995791459338E-314, height=2.121995791459338E-314)

坦率地说,我不知道如何解决上述问题:

以下是该类别的源文件:

-(UIImage *) createThumbnailToFillSize:(CGSize)size
{
    CGSize mainImageSize = self.size;//LINE WHERE IT CRASHES

    UIImage *thumb;

    CGFloat widthScaler = size.width / mainImageSize.width;
    CGFloat heightScaler = size.height / mainImageSize.height;

    CGSize repositionedMainImageSize = mainImageSize;

    CGFloat scaleFactor;
    // Determine if we should shrink based on width or hight
    if(widthScaler > heightScaler)
    {
        // calculate based on width scaler
        scaleFactor = widthScaler;
        repositionedMainImageSize.height = ceil(size.height / scaleFactor);
    }
    else {
        // calculate based on height scaler
        scaleFactor = heightScaler;
        repositionedMainImageSize.width = ceil(size.width / heightScaler);
    }

    UIGraphicsBeginImageContext(size);

    CGFloat xInc = ((repositionedMainImageSize.width-mainImageSize.width) / 2.f) *scaleFactor;
    CGFloat yInc = ((repositionedMainImageSize.height-mainImageSize.height) / 2.f) *scaleFactor;

    [self drawInRect:CGRectMake(xInc, yInc, mainImageSize.width * scaleFactor, mainImageSize.height * scaleFactor)];
    thumb = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return thumb;
}

以下是它的调用方式。

 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

        UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
        //thumbnail stuff
        CGFloat side = 71.f;//was 71 in Kuh book
        side *=[[UIScreen mainScreen] scale];
        UIImage *thumbnail = [chosenImage createThumbnailToFillSize:CGSizeMake(side, side)];
        self.imageView.image = thumbnail;

欢迎任何有关导致崩溃的建议。

0 个答案:

没有答案