Skip to content

Instantly share code, notes, and snippets.

@rtanote
Created May 19, 2013 02:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rtanote/5606386 to your computer and use it in GitHub Desktop.
Save rtanote/5606386 to your computer and use it in GitHub Desktop.
processingのmap関数をC#で使えるように。ジェネリックメソッド&拡張メソッドにしている。
public static class MiscUtils
{
/// <summary>
/// Re-maps a number from one range to another.
/// </summary>
/// <typeparam name="Type">IConvertible-implementing type</typeparam>
/// <param name="value">the incoming value to be converted</param>
/// <param name="start1">lower bound of the value's current range</param>
/// <param name="stop1">upper bound of the value's current range</param>
/// <param name="start2">lower bound of the value's target range</param>
/// <param name="stop2">upper bound of the value's target range</param>
/// <returns></returns>
public static Type Map<Type>(this Type value, Type start1, Type stop1, Type start2, Type stop2) where Type : IConvertible {
double mappedValue
= start2.ToDouble(NumberFormatInfo.CurrentInfo)
+ (stop2.ToDouble(NumberFormatInfo.CurrentInfo) - start2.ToDouble(NumberFormatInfo.CurrentInfo))
* ((value.ToDouble(NumberFormatInfo.CurrentInfo) - start1.ToDouble(NumberFormatInfo.CurrentInfo))
/ (stop1.ToDouble(NumberFormatInfo.CurrentInfo) - start1.ToDouble(NumberFormatInfo.CurrentInfo)));
return (Type)Convert.ChangeType(mappedValue, typeof(Type));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment