如何从UIColor获取色调,饱和度和亮度? [英] How do i get the hue, saturation and brightness from a UIColor?

查看:187
本文介绍了如何从UIColor获取色调,饱和度和亮度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从UIColor中获取单个值.不确定如何做?

I want to get the individual values from a UIColor. Unsure how to do it?

推荐答案

static void RGBtoHSV( float r, float g, float b, float *h, float *s, float *v )
{
    float min, max, delta;
    min = MIN( r, MIN( g, b ));
    max = MAX( r, MAX( g, b ));
    *v = max;               // v
    delta = max - min;
    if( max != 0 )
        *s = delta / max;       // s
    else {
        // r = g = b = 0        // s = 0, v is undefined
        *s = 0;
        *h = -1;
        return;
    }
    if( r == max )
        *h = ( g - b ) / delta;     // between yellow & magenta
    else if( g == max )
        *h = 2 + ( b - r ) / delta; // between cyan & yellow
    else
        *h = 4 + ( r - g ) / delta; // between magenta & cyan
    *h *= 60;               // degrees
    if( *h < 0 )
        *h += 360;
}

static void HSVtoRGB( float *r, float *g, float *b, float h, float s, float v )
{
    int i;
    float f, p, q, t;
    if( s == 0 ) {
        // achromatic (grey)
        *r = *g = *b = v;
        return;
    }
    h /= 60;            // sector 0 to 5
    i = floor( h );
    f = h - i;          // factorial part of h
    p = v * ( 1 - s );
    q = v * ( 1 - s * f );
    t = v * ( 1 - s * ( 1 - f ) );
    switch( i ) {
        case 0:
            *r = v;
            *g = t;
            *b = p;
            break;
        case 1:
            *r = q;
            *g = v;
            *b = p;
            break;
        case 2:
            *r = p;
            *g = v;
            *b = t;
            break;
        case 3:
            *r = p;
            *g = q;
            *b = v;
            break;
        case 4:
            *r = t;
            *g = p;
            *b = v;
            break;
        default:        // case 5:
            *r = v;
            *g = p;
            *b = q;
            break;
    }
}

...

CGFloat r, g, b, a, h, s, v;

const CGFloat *comp = CGColorGetComponents([myUIColor CGColor]);

r = comp[0];
g = comp[1];
b = comp[2];
a = comp[3];

RGBtoHSV(r, g, b, &h, &s, &v);

上面的代码假定UIColor是在RGB空间中设置的(典型值).如果该颜色在另一个颜色空间中,它将崩溃和/或具有未定义的行为.

The code above assumes the UIColor is setup in the RGB space (which is typical). If the color is in another color space it will crash and / or have undefined behavior.

iOS 5.0具有- (BOOL)getHue:(CGFloat *)hue saturation:(CGFloat *)saturation brightness:(CGFloat *)brightness alpha:(CGFloat *)alpha,它可以为您完成所有这些工作.但这还不可用.

iOS 5.0 has - (BOOL)getHue:(CGFloat *)hue saturation:(CGFloat *)saturation brightness:(CGFloat *)brightness alpha:(CGFloat *)alpha which does all this work for you. But it's not available yet.

这篇关于如何从UIColor获取色调,饱和度和亮度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆