
xcode
Voglio illustrarvi come ottenere da un NSColor una NSString che contiene il codice esadecomale del colore.
Objective-c mette a disposizione degli sviluppatori le Categories(in soldoni la possibilità di aggiungere metodi alle classi senza creare sottoclassi) e noi utilizzeremo proprio questa caratteristica del linguaggio per aggiungere un metodo “hexValue” che ci restituisce la string in esadecimale:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | #import <Cocoa/Cocoa.h> @interface NSColor(NSColorHex) -(NSString *)hexValue; @end #import "NSColorHex.h" @implementation NSColor(NSColorHex) -(NSString *)hexValue{ float redFloatValue, greenFloatValue, blueFloatValue; int redIntValue, greenIntValue, blueIntValue; NSString *redHexValue, *greenHexValue, *blueHexValue; NSColor *convertedColor=[self colorUsingColorSpaceName:NSCalibratedRGBColorSpace]; if(convertedColor) { // Get the red, green, and blue components of the color //[convertedColor getRed:&redFloatValue green:&greenFloatValue blue:&blueFloatValue alpha:NULL]; redFloatValue =[convertedColor redComponent]; blueFloatValue=[convertedColor blueComponent]; greenFloatValue=[convertedColor greenComponent]; // Convert the components to numbers (unsigned decimal integer) between 0 and 255 redIntValue=redFloatValue*255.99999f; greenIntValue=greenFloatValue*255.99999f; blueIntValue=blueFloatValue*255.99999f; // Convert the numbers to hex strings redHexValue=[NSString stringWithFormat:@"%02x", redIntValue]; greenHexValue=[NSString stringWithFormat:@"%02x", greenIntValue]; blueHexValue=[NSString stringWithFormat:@"%02x", blueIntValue]; // Concatenate the red, green, and blue components' hex strings together with a "#" return [NSString stringWithFormat:@"%@%@%@", redHexValue, greenHexValue, blueHexValue]; } return nil; } |
Ora vediamo come utilizzare quanto scritto sopra:
1 2 3 4 5 6 7 | //Ricordatevi di fare #import "NSColorHex.h" in cima al file NSColor *colore=[NSColor blueColor]; NSString *esadecimale=[colore hexValue]; NSLog(@"%@",esadecimale); |