首页 文章

调整UIImage高度,同时保持其纵横比(iOS)[重复]

提问于
浏览
0

这个问题在这里已有答案:

我正在使用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
    +(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

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

    伪代码

    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];
    }
    

相关问题