ウォーレン氏のコードを試しましたが、信頼できる結果が得られませんでした。例えば
、あなたが見ることができる
ExpandToBound(new Size(640,480), new Size(66, 999)).Dump();
// {Width=66, Height=49}
ExpandToBound(new Size(640,480), new Size(999,50)).Dump();
// {Width=66, Height=50}
、高さ= 49、高さ=別では50。
ここは私のものです(Mr.
// Passing null for either maxWidth or maxHeight maintains aspect ratio while
// the other non-null parameter is guaranteed to be constrained to
// its maximum value.
//
// Example: maxHeight = 50, maxWidth = null
// Constrain the height to a maximum value of 50, respecting the aspect
// ratio, to any width.
//
// Example: maxHeight = 100, maxWidth = 90
// Constrain the height to a maximum of 100 and width to a maximum of 90
// whichever comes first.
//
private static Size ScaleSize(Size from, int? maxWidth, int? maxHeight)
{
if (!maxWidth.HasValue && !maxHeight.HasValue) throw new ArgumentException("At least one scale factor (toWidth or toHeight) must not be null.");
if (from.Height == 0 || from.Width == 0) throw new ArgumentException("Cannot scale size from zero.");
double? widthScale = null;
double? heightScale = null;
if (maxWidth.HasValue)
{
widthScale = maxWidth.Value/(double)from.Width;
}
if (maxHeight.HasValue)
{
heightScale = maxHeight.Value/(double)from.Height;
}
double scale = Math.Min((double)(widthScale ?? heightScale),
(double)(heightScale ?? widthScale));
return new Size((int)Math.Floor(from.Width * scale), (int)Math.Ceiling(from.Height * scale));
}
乱用しないでください、引用文献のように呼び出します。 widthとheightフィールドを持つ_immutable_ structのRectangleを作成し、2つのRectangleを取り、結果のRectangleを返すExpandToBoundメソッドを作成する方が良いでしょう。関数を_functions_として実装すると、関数の理由を考えるのがはるかに簡単です。引数が入り、結果が出ます。関数は所有していない状態を変更しません。 –
@ Eric Lippert - 合意しました。この例は、私が実際に実装した関数ではなく、問題の中核ではないRectangle構造体やその他のものとの混乱を避けるために煮詰めたバージョンです。 –