先贴上转换公式
直接上代码
+ (HSV)HSVFromRGB:(NSString *)RGB{
if ([RGB hasPrefix:@"#"]) {
RGB = [RGB substringFromIndex:1];
}
if (![RGB isLegal]) {
return HSVMake(0, 0, 0);
}
if (RGB.length == 3) {
RGB = [RGB stringByAppendingString:RGB];
}
NSString *Rs = [RGB substringToIndex:2];
NSString *Gs = [RGB substringWithRange:NSMakeRange(2, 2)];
NSString *Bs = [RGB substringFromIndex:4];
unsigned int Ri, Gi, Bi;
NSScanner *scannerR = [NSScanner scannerWithString:Rs];
NSScanner *scannerG = [NSScanner scannerWithString:Gs];
NSScanner *scannerB = [NSScanner scannerWithString:Bs];
[scannerR scanHexInt:&Ri];
[scannerG scanHexInt:&Gi];
[scannerB scanHexInt:&Bi];
CGFloat Rf = (double)Ri/255.0;
CGFloat Gf = (double)Gi/255.0;
CGFloat Bf = (double)Bi/255.0;
CGFloat Cmax = [(id)[CHelps CMaxWithArray:@[@(Rf),@(Gf),@(Bf)]] floatValue];
CGFloat Cmin = [(id)[CHelps CMinWithArray:@[@(Rf),@(Gf),@(Bf)]] floatValue];
CGFloat Cdiff = Cmax - Cmin;
CGFloat H, S, V;
if (Cdiff == 0) {
H = 0;
}else {
if (Cmax == Rf) {
H = 60*((Gf - Bf)/Cdiff + 0);
}else if (Cmax == Gf){
H = 60*((Bf - Rf)/Cdiff + 2);
}else{
H = 60*((Rf - Gf)/Cdiff + 4);
}
}
if (H < 0) {
H = H + 360;
}
H = H/360.0f;
if (Cmax == 0) {
S = 0;
}else{
S = Cdiff/Cmax;
}
V = Cmax;
HSV hsv = HSVMake(H, S, V);
return hsv;
}
尤其要注意最后色域H值虽是0度~360度,但在iOS上是H/360.0f。
对比了很长时间,值都对,就是颜色不对,原来是因为这。