首页 文章

使用宽高比调整UIImage的大小?

提问于
浏览
34

我正在使用此代码调整iPhone上的图像大小:

CGRect screenRect = CGRectMake(0, 0, 320.0, 480.0);
UIGraphicsBeginImageContext(screenRect.size);
[value drawInRect:screenRect blendMode:kCGBlendModePlusDarker alpha:1];
UIImage *tmpValue = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

只要图像的宽高比与新调整大小的图像的宽高比相匹配,哪个工作正常 . 我想修改它,以便保持正确的宽高比,并在图像不显示的任何地方放置黑色背景 . 所以我仍然会得到一张320x480的图像,但在顶部和底部或两侧都有黑色,具体取决于原始图像尺寸 .

有没有一种简单的方法来做到这一点类似于我正在做的事情?谢谢!

1 回答

  • 52

    设置屏幕rect后,执行以下操作以确定绘制图像的矩形:

    float hfactor = value.bounds.size.width / screenRect.size.width;
    float vfactor = value.bounds.size.height / screenRect.size.height;
    
    float factor = fmax(hfactor, vfactor);
    
    // Divide the size by the greater of the vertical or horizontal shrinkage factor
    float newWidth = value.bounds.size.width / factor;
    float newHeight = value.bounds.size.height / factor;
    
    // Then figure out if you need to offset it to center vertically or horizontally
    float leftOffset = (screenRect.size.width - newWidth) / 2;
    float topOffset = (screenRect.size.height - newHeight) / 2;
    
    CGRect newRect = CGRectMake(leftOffset, topOffset, newWidth, newHeight);
    

    如果您不想放大小于screenRect的图像,请确保 factor 大于或等于1(例如 factor = fmax(factor, 1) ) .

    要获得黑色背景,您可能只想将上下文颜色设置为黑色并在绘制图像之前调用fillRect .

相关问题