如何在保持其纵横比的同时调整 UIImage 的大小

How to resize an UIImage while maintaining its Aspect Ratio(如何在保持其纵横比的同时调整 UIImage 的大小)

本文介绍了如何在保持其纵横比的同时调整 UIImage 的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调整 UIImage 的大小并保持其纵横比.我已经编写了以下代码,但它没有按预期工作.

I want to resize a UIImage with maintaining its Aspect Ratio. I have written the following code, but it is not working as expected.

代码

-(UIImage * ) scaleImage: (UIImage * ) image toSize: (CGSize) targetSize {

    CGFloat scaleFactor = 1.0;
    if (image.size.width > targetSize.width || image.size.height > targetSize.height)
        if (!((scaleFactor = (targetSize.width / image.size.width)) > (targetSize.height / image.size.height))) //scale to fit width, or
            scaleFactor = targetSize.height / image.size.height; // scale to fit heigth.
    UIGraphicsBeginImageContext(targetSize);
    CGRect rect = CGRectMake((targetSize.width - image.size.width * scaleFactor) / 2, (targetSize.height - image.size.height * scaleFactor) / 2,
        image.size.width * scaleFactor, image.size.height * scaleFactor);
    [image drawInRect: rect];
    UIImage * scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

这里到底出了什么问题?

What exactly is wrong here?

推荐答案

我在几个项目中使用了类似的东西:

I'm using something similar to this in a few projects:

- (UIImage*) scaleImage:(UIImage*)image toSize:(CGSize)newSize {
    CGSize scaledSize = newSize;
    float scaleFactor = 1.0;
    if( image.size.width > image.size.height ) {
        scaleFactor = image.size.width / image.size.height;
        scaledSize.width = newSize.width;
        scaledSize.height = newSize.height / scaleFactor;
    }
    else {
        scaleFactor = image.size.height / image.size.width;
        scaledSize.height = newSize.height;
        scaledSize.width = newSize.width / scaleFactor;
    }

    UIGraphicsBeginImageContextWithOptions( scaledSize, NO, 0.0 );
    CGRect scaledImageRect = CGRectMake( 0.0, 0.0, scaledSize.width, scaledSize.height );
    [image drawInRect:scaledImageRect];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();    

    return scaledImage;
}

这篇关于如何在保持其纵横比的同时调整 UIImage 的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在保持其纵横比的同时调整 UIImage 的大小

基础教程推荐