在iOS中将图像裁剪为正方形

时间:2015-04-28 19:41:34

标签: ios image crop rotatetransform

在我的应用中,我使用UIImagePickerController从相机或照片库导入图像。比我将导入的图像保存到app文档目录。这一切都很好,但我想保存图像裁剪为正方形(如在instagram上),而不是它的原始尺寸。正方形应该是图像的宽度或其高度的大小(取决于哪个是较小的一个)。我想,也许CGRect在这里很有用,但我不知道如何从图像中裁剪出CGRect ..我看过无数的教程,但它们似乎都没有用,或者它们都太复杂了。

1 个答案:

答案 0 :(得分:0)

-(UIImage *)squareImage:(UIImage *)image
{
    if (image.size.width>=image.size.height)
    {
        image=[self imageWithImage:image scaledToHeight:100];
    }
    else
    {
    image=[self imageWithImage:image scaledToWidth:100];
    }

    return image;
}

-(UIImage*)imageWithImage:(UIImage*)sourceImage scaledToWidth:(float)width
{
    float oldWidth = sourceImage.size.width;
    float scaleFactor = width / oldWidth;

    float newHeight = sourceImage.size.height * scaleFactor;
    float newWidth = oldWidth * scaleFactor;

    UIGraphicsBeginImageContext(CGSizeMake(newWidth, newWidth));
    [sourceImage drawInRect:CGRectMake(0, 0, newWidth, newHeight)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

-(UIImage*)imageWithImage:(UIImage*)sourceImage scaledToHeight:(float)height
{
    float oldHeight = sourceImage.size.height;
    float scaleFactor = height / oldHeight;

    float newWidth = sourceImage.size.width * scaleFactor;
    float newHeight = oldHeight * scaleFactor;

    UIGraphicsBeginImageContext(CGSizeMake(newHeight, newHeight));
    [sourceImage drawInRect:CGRectMake(0, 0, newWidth, newHeight)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

上述方法将帮助您按比例缩放图像并将图像缩放为方形...旋转,您可以在谷歌上搜索。