13

uicolor を 16 進数の色に変換する際に問題が発生しました。

CGColorRef colorref = [[Colorview_ backgroundColor] CGColor];

int numComponents = CGColorGetNumberOfComponents(colorref);

if (numComponents == 4) {
    const CGFloat *components = CGColorGetComponents(colorref);

    int hexValue = 0xFF0000*components[0] + 0xFF00*components[1] + 0xFF*components[2];

    NSString *hexString = [NSString stringWithFormat:@"#%d", hexValue];
}

このコードは私に #5576149 (たとえば) hexString を与えています。6 桁ではなく 7 桁であることがわかります。16 進数の色ではありません。

4

4 に答える 4

13

上記のsylphosの答えは、darkGrayColorでは機能しません。

これはうまく機能します(http://softteco.blogspot.jp/2011/06/extract-hex-rgb-color-from-uicolor.htmlから取得):

- (NSString *) hexFromUIColor:(UIColor *)color {
    if (CGColorGetNumberOfComponents(color.CGColor) < 4) {
        const CGFloat *components = CGColorGetComponents(color.CGColor);
        color = [UIColor colorWithRed:components[0] green:components[0] blue:components[0] alpha:components[1]];
    }
    if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) != kCGColorSpaceModelRGB) {
        return [NSString stringWithFormat:@"#FFFFFF"];
    }
    return [NSString stringWithFormat:@"#%02X%02X%02X", (int)((CGColorGetComponents(color.CGColor))[0]*255.0), (int)((CGColorGetComponents(color.CGColor))[1]*255.0), (int)((CGColorGetComponents(color.CGColor))[2]*255.0)];
}
于 2012-10-30T07:17:11.453 に答える
2
NSString *hexString = [NSString stringWithFormat:@"#%d", hexValue];

%d で数字としてフォーマットしています

%x または %X を使用して 16 進数としてフォーマットする必要があります -- おそらく文字列 %s として、関数が何をしていて、何int hexValueが保持されているかを確認しませんでした

d または i 符号付き 10 進整数 392

x 符号なし 16 進整数 7fa

X 符号なし 16 進整数 (大文字) 7FA

于 2012-04-23T17:39:20.097 に答える
2

uicolor から 16 進数の色を取得する必要があり、javascript でも機能させる必要があったため、昨日試してみましたが、00 ではなく 0 を取得するため、コンポーネントが 0 の場合は機能しません。したがって、純粋なシアンはRGB 0 255 255 の場合、このコードは #00ffff ではなく #0ffff を返します。

私はあなたのものからこのコードを作成しましたが、それは私のアプリで動作しています:

-(NSString*)colorToHex:(UIColor*)color{

    CGColorRef colorref = [color CGColor];

    const CGFloat *components = CGColorGetComponents(colorref);

    NSString *hexString = @"#";
    int hexValue = 0;

    for (int i=0; i<3; i++) {
        if (components[i] == 0) {
            hexString = [NSString stringWithFormat:@"%@00", hexString];
        }else{
            hexValue = 0xFF*components[i];
            hexString = [NSString stringWithFormat:@"%@%x", hexString, hexValue];
        }
    }

    return hexString;
}
于 2012-07-31T18:16:01.717 に答える