Question

J'ai un code hexagonal RVB comme #ffffff en tant que nsstring et je veux convertir cela en UIColor. Y a-t-il un moyen simple de faire cela?

Était-ce utile?

La solution

Dans un de mes code, J'utilise 2 fonctions différentes:

void SKScanHexColor(NSString * hexString, float * red, float * green, float * blue, float * alpha) {
  NSString *cleanString = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""];
  if([cleanString length] == 3) {
      cleanString = [NSString stringWithFormat:@"%@%@%@%@%@%@", 
                     [cleanString substringWithRange:NSMakeRange(0, 1)],[cleanString substringWithRange:NSMakeRange(0, 1)],
                     [cleanString substringWithRange:NSMakeRange(1, 1)],[cleanString substringWithRange:NSMakeRange(1, 1)],
                     [cleanString substringWithRange:NSMakeRange(2, 1)],[cleanString substringWithRange:NSMakeRange(2, 1)]];
  }
  if([cleanString length] == 6) {
      cleanString = [cleanString stringByAppendingString:@"ff"];
  }

  unsigned int baseValue;
  [[NSScanner scannerWithString:cleanString] scanHexInt:&baseValue];

  if (red) { *red = ((baseValue >> 24) & 0xFF)/255.0f; }
  if (green) { *green = ((baseValue >> 16) & 0xFF)/255.0f; }
  if (blue) { *blue = ((baseValue >> 8) & 0xFF)/255.0f; }
  if (alpha) { *alpha = ((baseValue >> 0) & 0xFF)/255.0f; }
}

Et puis je l'utilise comme ceci:

UIColor * SKColorFromHexString(NSString * hexString) {
  float red, green, blue, alpha;
  SKScanHexColor(hexString, &red, &green, &blue, &alpha);

  return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}

Si vous préférez l'utiliser comme un UIColor Catégorie, alors il s'agit juste de modifier quelques lignes:

+ (UIColor *) colorFromHexString:(NSString *)hexString {
  NSString *cleanString = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""];
  if([cleanString length] == 3) {
      cleanString = [NSString stringWithFormat:@"%@%@%@%@%@%@", 
                     [cleanString substringWithRange:NSMakeRange(0, 1)],[cleanString substringWithRange:NSMakeRange(0, 1)],
                     [cleanString substringWithRange:NSMakeRange(1, 1)],[cleanString substringWithRange:NSMakeRange(1, 1)],
                     [cleanString substringWithRange:NSMakeRange(2, 1)],[cleanString substringWithRange:NSMakeRange(2, 1)]];
  }
  if([cleanString length] == 6) {
      cleanString = [cleanString stringByAppendingString:@"ff"];
  }

  unsigned int baseValue;
  [[NSScanner scannerWithString:cleanString] scanHexInt:&baseValue];

  float red = ((baseValue >> 24) & 0xFF)/255.0f;
  float green = ((baseValue >> 16) & 0xFF)/255.0f;
  float blue = ((baseValue >> 8) & 0xFF)/255.0f;
  float alpha = ((baseValue >> 0) & 0xFF)/255.0f;

  return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}

Cela gérera les chaînes comme "#abc", "# ABCDEF31", etc.

Autres conseils

Si vous utilisez des valeurs hexagonales.

#define UIColorFromRGB(rgbValue) [UIColor \
       colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
       green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
       blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

  //Then use any Hex value

 self.view.backgroundColor = UIColorFromRGB(0xD2691E);   

Je cherchais une solution simple et je suis venu avec cela (pas complètement objectif-c, mais fonctionne comme un charme):

NSString *stringColor = @"#AABBCC";
NSUInteger red, green, blue;
sscanf([stringColor UTF8String], "#%02X%02X%02X", &red, &green, &blue);

UIColor *color = [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1];

Il y a une belle catégorie pour Uicolor appelée "Uicolor + élargi" qui a une méthode de classe pour obtenir un UICOLOR à partir d'une chaîne HEX RVB:

C'est simple à utiliser:

UIColor *myColor = [UIColor colorWithHexString:@"FF0000"];

De plus, il ajoute beaucoup d'autres utilitaires potentiellement utiles à UIColor. Plus d'informations sont disponibles dans Cet article.

Facile, allez simplement sur ce site Web et saisissez votre valeur hexadécimale: http://www.corecoding.com/utilities/rgb-or-hex-to-float.php

+ (UIColor *)colorWithHexString:(NSString *)colorString
{
    colorString = [colorString stringByReplacingOccurrencesOfString:@"#" withString:@""];

    if (colorString.length == 3)
        colorString = [NSString stringWithFormat:@"%c%c%c%c%c%c",
        [colorString characterAtIndex:0], [colorString characterAtIndex:0],
        [colorString characterAtIndex:1], [colorString characterAtIndex:1],
        [colorString characterAtIndex:2], [colorString characterAtIndex:2]];

    if (colorString.length == 6)
    {
        int r, g, b;
        sscanf([colorString UTF8String], "%2x%2x%2x", &r, &g, &b);
        return [UIColor colorWithRed:(r/255.0) green:(g/255.0) blue:(b/255.0) alpha:1.0];
    }
    return nil;
}

Pour le format # 123, 123, # FFF195, FFF195

+ (UIColor *)colorWithHexValue:(int)hexValue
{
    float red   = ((hexValue & 0xFF0000) >> 16)/255.0;
    float green = ((hexValue & 0xFF00) >> 8)/255.0;
    float blue  = (hexValue & 0xFF)/255.0;
    return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}

pour le format 0xfff195

La manière la plus simple que j'ai trouvée: Convertisseur hexadécimal à uicolor

Tapez simplement le numéro hexadécimal sans «#», et il renvoie le code UICOLOR. Par exemple, le code pour la couleur orange (# f77f00) est:

[UIColor colorWithRed:0.969 green:0.498 blue:0 alpha:1.0]

Je pense que j'avais divisé les six personnages en trois paires, puis convertir cela en décimal, puis diviser cela par 255 pour obtenir chaque composant de couleur sous forme de flotteur.

Vous pouvez ensuite passer les composants à:

[UIColor colorWithRed: green: blue: alpha:1];

J'ai créé un outil en ligne pour convertir instantanément n'importe quel code hexagonal en un extrait de code UIColor pour Swift et Objective-C, car quand il est gênant d'utiliser des méthodes ou des plugins personnalisés: https://iosref.com/uihex/

Si vous ne souhaitez pas écrire tout ce code ci-dessus, vous pouvez vérifier ce site: http://www.diovo.com/apps/rgb-to-uicolor-converter.html
D'une couleur hexagonale comme ceci: #ffffff, le site le convertit dans une chaîne comme ceci:

UIColor *aColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1.000];

Si la conversion d'Objective à Swift est difficile pour vous, voici la réponse avec Swift. Actuellement, il ne prend que des chaînes sans le #, mais vous pouvez ajouter une méthode de scanner pour le sauter, je crois.

func stringToColor(stringColor: String) -> UIColor {
    var hexInt: UInt32 = 0
    let scanner = NSScanner(string: stringColor)
    scanner.scanHexInt(&hexInt)
    let color = UIColor(
        red: CGFloat((hexInt & 0xFF0000) >> 16)/255,
        green: CGFloat((hexInt & 0xFF00) >> 8)/255,
        blue: CGFloat((hexInt & 0xFF))/255,
        alpha: 1)

    return color
}

N'oubliez pas que vous avez la possibilité de Convertissez vos valeurs hexadécimales en RVB et entrez-les dans le constructeur d'interface. Cela économisera quelques lignes de code.

rgb sliders

Je suppose que c'est un peu tard ici ... mais j'ai trouvé cette version dans le Repo Github Whitehouse qui le fait d'une manière assez élégante:

+(UIColor *)colorFromRGBHexString:(NSString *)colorString {
    if(colorString.length == 7) {
        const char *colorUTF8String = [colorString UTF8String];
        int r, g, b;
        sscanf(colorUTF8String, "#%2x%2x%2x", &r, &g, &b);
        return [UIColor colorWithRed:(r / 255.0) green:(g / 255.0) blue:(b / 255.0) alpha:1.0];
    }    
    return nil;
}

Lien source vers leur whappconfig.m sur github

Je pense qu'il existe un moyen encore plus facile lors de l'utilisation de valeurs hexadécimales. Ajoutez simplement une définition en haut de votre fichier ou référencez un fichier d'en-tête pour la conversion (UICOLORFROMRGB). Vous pouvez même ajouter un modèle de valeurs de couleur hexagonale fixes.

#define CLR_YELLOW_TEXT     0xf4dc89    // A Light Yellow text
#define CLR_GREEN_TEXT      0x008040    // Dark Green text for my buttons

#define UIColorFromRGB(rgbValue)  [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

Ensuite, référez-le dans votre code en utilisant directement les valeurs hexagonales ou vos valeurs hexadécimales définies. Par exemple...

[myButton1 setTitleColor:UIColorFromRGB(0xd02d2d) forState:UIControlStateNormal];
[myButton2 setTitleColor:UIColorFromRGB(CLR_GREEN_TEXT) forState:UIControlStateNormal];
[myButton3 setTitleColor:UIColorFromRGB(CLR_YELLOW_TEXT) forState:UIControlStateNormal];

(PS - Cela suppose un alpha de 1.0, mais il peut toujours être modifié dans la définition).

Prendre plaisir.

J'ai trouvé une bibliothèque cocoapod très utile pour créer des valeurs uicolor en utilisant des valeurs "#rrggbb".

pod 'UIColor-HexRGB'
+(UIColor*)colorWithHexString:(NSString*)hexString

{

NSString *cString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

if ([cString length] < 6) return [UIColor grayColor];

if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];

if ([cString length] != 6) return  [UIColor grayColor];

NSRange range;
range.location = 0;
range.length = 2;
NSString *rString = [cString substringWithRange:range];

range.location = 2;
NSString *gString = [cString substringWithRange:range];

range.location = 4;
NSString *bString = [cString substringWithRange:range];

unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];

return [UIColor colorWithRed:((float) r / 255.0f)
                       green:((float) g / 255.0f)
                        blue:((float) b / 255.0f)
                       alpha:1.0f];

}

J'ai fini par créer une catégorie pour UIColor que je peux simplement réutiliser mes autres projets.

Objectif c

#import <UIKit/UIKit.h>

@interface UIColor (HexColor)

+ (UIColor *)colorFromHex:(unsigned long)hex;

@end

@implementation UIColor (HexColor)

+ (UIColor *)colorFromHex:(unsigned long)hex
{
  return [UIColor colorWithRed:((float)((hex & 0xFF0000) >> 16))/255.0 green:((float)((hex & 0xFF00) >> 8))/255.0 blue:((float)(hex & 0xFF))/255.0 alpha:1.0];
}

@end

// USAGE
UIColor *customRedColor = [UIColor colorFromHex:0x990000];

Rapide

extension UIColor {

  convenience init(hex: Int) {
    let red = CGFloat((hex & 0xff0000) >> 16) / 255.0
    let green = CGFloat((hex & 0x00ff00) >> 8) / 255.0
    let blue = CGFloat(hex & 0x0000ff) / 255.0
    self.init(red: red, green: green, blue: blue, alpha: 1.0)
  }

}

// USAGE
let customColor = UIColor(hex: 0x990000)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top