アスペクト比と幅を維持してUIImageのサイズを変更する 質問する

アスペクト比と幅を維持してUIImageのサイズを変更する 質問する

アスペクト比を維持したまま画像のサイズを変更する投稿を多数見てきました。これらの関数は、サイズ変更時に RECT の固定ポイント (幅と高さ) を使用します。ただし、私のプロジェクトでは、幅のみに基づいてビューのサイズを変更する必要があり、高さはアスペクト比に基づいて自動的に取得される必要があります。これを実現するのを手伝ってくれる人はいますか。

ベストアンサー1

スリカール法は、高さと幅の両方が分かっていれば非常に有効です。そして新しいサイズの幅。たとえば、拡大縮小する幅だけがわかっていて、高さは気にしない場合は、まず高さのスケール係数を計算する必要があります。

+(UIImage*)imageWithImage: (UIImage*) sourceImage scaledToWidth: (float) i_width
{
    float oldWidth = sourceImage.size.width;
    float scaleFactor = i_width / oldWidth;

    float newHeight = sourceImage.size.height * scaleFactor;
    float newWidth = oldWidth * scaleFactor;

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

おすすめ記事