调整UIImage高度同时保持其纵横比(iOS)

时间:2015-07-08 17:46:20

标签: ios objective-c

我正在使用UIImagePickerController从我的库中选择一个图像并将其上传到Parse。我怎样才能调整图像的高度?我希望图像保持宽高比,但我不希望高度高于1000px。

现在我正在使用以下代码将宽度和高度调整为固定数字:

ViewController.h

- (UIImage *)resizeImage:(UIImage *)image toWidth:(float)width andHeight:(float)height;

ViewController.h

- (UIImage *)resizeImage:(UIImage *)image toWidth:(float)width andHeight:(float)height {
    CGSize newSize = CGSizeMake(width, height);
    CGRect newRectangle = CGRectMake(0, 0, width, height);
    UIGraphicsBeginImageContext(newSize);
    [self.image drawInRect:newRectangle];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return resizedImage;
}

- (IBAction)createProduct:(id)sender {
    UIImage *newImage = [self resizeImage:self.image toWidth:750.0f andHeight:1000.0f];
    NSData *imageData = UIImagePNGRepresentation(newImage);
    PFFile *imageFile = [PFFile fileWithName:@"image.jpg" data:imageData];
}

感谢。

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

您必须获得原始尺寸的纵横比并将其乘以新的高度

伪代码

if (height > 1000){
    aspectRatio = width/height;
    height = 1000;
    width = height * aspectRatio
}
- (IBAction)createProduct:(id)sender {
    UIImage *newImage;
    if (self.image.size.height > 1000){
        CGFloat aspectRatio = self.image.size.width/self.image.size.height;
        CGFloat height = 1000;
        CGFloat width = height * aspectRatio;
        newImage = [self resizeImage:self.image toWidth:width andHeight:height];
    } else {
        newImage = self.image;
    }


    NSData *imageData = UIImagePNGRepresentation(newImage);
    PFFile *imageFile = [PFFile fileWithName:@"image.jpg" data:imageData];
}