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

前端之家收集整理的这篇文章主要介绍了ios – 如何调整UIImage的大小,同时保持其纵横比前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想调整UIImage的大小,同时保持其纵横比.我已经写了下面的代码,但是没有按预期的方式工作.

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

这里究竟是错的?

@H_301_9@解决方法
我在几个项目中使用类似的东西:
- (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;
}
原文链接:https://www.f2er.com/iOS/337613.html

猜你在找的iOS相关文章