Skip to content

Instantly share code, notes, and snippets.

@wileywimberly
Last active August 29, 2015 14:01
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 wileywimberly/2f470fab2b95c47b6479 to your computer and use it in GitHub Desktop.
Save wileywimberly/2f470fab2b95c47b6479 to your computer and use it in GitHub Desktop.
Map a value from one range to another. In this example map the angle of a line to a hue.
#import <Foundation/Foundation.h>
@interface BNRLine : NSObject
@property (nonatomic) CGPoint begin;
@property (nonatomic) CGPoint end;
- (CGFloat)angleInRadians;
- (CGFloat)angleInDegrees;
- (UIColor *)lineColor;
@end
#import "BNRLine.h"
@implementation BNRLine
- (CGFloat)angleInRadians
{
CGPoint begin = self.begin;
CGPoint end = self.end;
CGFloat dx = end.x - begin.x;
CGFloat dy = begin.y - end.y;
CGFloat angle = atan2f(dy, dx);
if (angle < 0) {
angle += (2 * M_PI);
}
return angle;
}
- (CGFloat)angleInDegrees
{
return [self angleInRadians] * 180.0 / M_PI;
}
- (CGFloat)hue
{
return [self mapToNewRangeWithValue:[self angleInRadians]
oldMin:0.0 oldMax:2.0 * M_PI
newMin:0.0 newMax:1.0];
}
- (UIColor *)lineColor
{
return [UIColor colorWithHue:[self hue] saturation:1.0 brightness:1.0 alpha:1.0];
}
- (CGFloat)mapToNewRangeWithValue:(CGFloat)oldValue
oldMin:(CGFloat)oldMin
oldMax:(CGFloat)oldMax
newMin:(CGFloat)newMin
newMax:(CGFloat)newMax
{
CGFloat oldRangeWidth = (oldMax - oldMin); // width of old range
CGFloat newRangeWidth = (newMax - newMin); // width of new range
CGFloat distanceFromMinInOldRange = oldValue - oldMin;
CGFloat normalizedValue = distanceFromMinInOldRange / oldRangeWidth; // [0, 1]
CGFloat newValue = normalizedValue * newRangeWidth + newMin; // expand to new range and shift over
return newValue;
};
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment