Permalink
Browse files

• add an OakStringToColorTransformer — this can be used as the value …

…transformer for a color picker and will store the color as #RRGGBB.

In retrospect, the value transformers should probably have been using the TMD prefix.
  • Loading branch information...
1 parent ce4da4a commit 0c88a5d19680ae5a02da65c9a0eb1ab94b4a6a76 @sorbits sorbits committed Jun 26, 2007
Showing with 45 additions and 0 deletions.
  1. +3 −0 ValueTransformers.h
  2. +42 −0 ValueTransformers.mm
View
@@ -5,3 +5,6 @@
@interface OakIntArrayToIndexSetTransformer : NSValueTransformer
@end
+
+@interface OakStringToColorTransformer : NSValueTransformer
+@end
View
@@ -82,3 +82,45 @@ - (id)reverseTransformedValue:(id)value
return array;
}
@end
+
+// =============================================
+// = #RRGGBB String To Color Value Transformer =
+// =============================================
+
+static NSColor* NSColorFromString (NSString* aColor)
+{
+ if(!aColor || [aColor isEqualToString:@""])
+ return nil;
+
+ unsigned int red = 0, green = 0, blue = 0, alpha = 0xFF;
+ if(sscanf([aColor UTF8String], "#%02x%02x%02x%02x", &red, &green, &blue, &alpha) < 3)
+ return nil;
+
+ return [NSColor colorWithCalibratedRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:alpha/255.0f];
+}
+
+static NSString* NSStringFromColor (NSColor* aColor)
+{
+ if(aColor == nil)
+ return nil;
+
+ aColor = [aColor colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
+ if([aColor alphaComponent] != 1.0f)
+ return [NSString stringWithFormat:@"#%02X%02X%02X%02X", lroundf(255.0f*[aColor redComponent]), lroundf(255.0f*[aColor greenComponent]), lroundf(255.0f*[aColor blueComponent]), lroundf(255.0f*[aColor alphaComponent])];
+ else return [NSString stringWithFormat:@"#%02X%02X%02X", lroundf(255.0f*[aColor redComponent]), lroundf(255.0f*[aColor greenComponent]), lroundf(255.0f*[aColor blueComponent])];
+}
+
+@implementation OakStringToColorTransformer
++ (Class)transformedValueClass { return [NSColor class]; }
++ (BOOL)allowsReverseTransformation { return YES; }
+
+- (id)transformedValue:(id)value { return NSColorFromString(value); }
+- (id)reverseTransformedValue:(id)value { return NSStringFromColor(value); }
+
++ (void)load
+{
+ id transformer = [self new];
+ [NSValueTransformer setValueTransformer:transformer forName:@"OakStringToColorTransformer"];
+ [transformer release];
+}
+@end

0 comments on commit 0c88a5d

Please sign in to comment.