श्री वॉरेन के कोड का प्रयास किया, लेकिन इससे विश्वसनीय परिणाम नहीं मिले।
उदाहरण के लिए
,
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 किसी अन्य रूप में।
यहां मेरा (आधारित श्रीमान संस्करण है।वॉरेन कोड) विसंगति और एक मामूली refactor बिना:
// 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));
}
स्रोत
2011-03-20 10:28:09
उस तरह कृपया दुरुपयोग नहीं refs कहते हैं। एक _immutable_ संरचना आयत बनाने के लिए काफी बेहतर है जिसमें चौड़ाई और ऊंचाई फ़ील्ड है, और फिर एक विधि लिखें ExpandToBound जो दो आयताकार लेता है और परिणामी आयताकार देता है। जब आप उन्हें _functions_ के रूप में कार्यान्वित करते हैं तो कार्यों के बारे में कारण बनाना बहुत आसान है। तर्क आते हैं, परिणाम आते हैं; कार्य राज्य को म्यूट नहीं करते हैं कि उनके पास स्वामित्व नहीं है। –
@ एरिक लिपर्ट - सहमत, उदाहरण वास्तव में कार्यान्वित नहीं किया गया था, उदाहरण के लिए एक उबला हुआ संस्करण, आयताकार structs या अन्य चीजों के साथ समस्या को भ्रमित करने से बचने के लिए जो समस्या के मूल का हिस्सा नहीं हैं। –