我正在使用以下代码创建一个颜色对象.
curView.backgroundColor = [[UIColor alloc] initWithHue:229 saturation:40 brightness:75 alpha:1];
如何从创建的颜色对象中检索RGB值?
在iOS 5中,您可以使用:
CGFloat red = 0.0, green = 0.0, blue = 0.0, alpha =0.0; [multipliedColor getRed:&red green:&green blue:&blue alpha:&alpha];
const CGFloat *colors = CGColorGetComponents( curView.backgroundColor.CGColor );
这些链接提供了更多细节:
UIColor参考
CGColorGetComponents参考
SWIFT 3和4
我发现cgColor.components并不总是返回4个颜色值,所以我改变了这个,所以它从CIColor包装器中获取它们
extension UIColor { var redValue: CGFloat{ return CIColor(color: self).red } var greenValue: CGFloat{ return CIColor(color: self).green } var blueValue: CGFloat{ return CIColor(color: self).blue } var alphaValue: CGFloat{ return CIColor(color: self).alpha } }
SWIFT 2
extension UIColor { var red: CGFloat{ return CGColorGetComponents(self.CGColor)[0] } var green: CGFloat{ return CGColorGetComponents(self.CGColor)[1] } var blue: CGFloat{ return CGColorGetComponents(self.CGColor)[2] } var alpha: CGFloat{ return CGColorGetComponents(self.CGColor)[3] } }
这不是最有效的方式,所以我不会在不断重新绘制视图的情况下使用它.
希望这会有所帮助
CGFloat red, green, blue, alpha; //Create a sample color UIColor *redColor = [UIColor redColor]; //Call [redColor getRed: &red green: &green blue: &blue alpha: &alpha]; NSLog(@"red = %f. Green = %f. Blue = %f. Alpha = %f", red, green, blue, alpha);
刚刚为此做了一个类别.
NSLog(@"%f", [UIColor blueColor].blue); // 1.000000
是这样的:
typedef enum { R, G, B, A } UIColorComponentIndices; @implementation UIColor (EPPZKit) -(CGFloat)red { return CGColorGetComponents(self.CGColor)[R]; } -(CGFloat)green { return CGColorGetComponents(self.CGColor)[G]; } -(CGFloat)blue { return CGColorGetComponents(self.CGColor)[B]; } -(CGFloat)alpha { return CGColorGetComponents(self.CGColor)[A]; } @end
部分eppz!kit
与更多UIColor好吃的东西.
const float* colors = CGColorGetComponents( curView.backgroundColor.CGColor );
谢谢.我不得不const
在行的开头添加它,因为它正在生成警告.
UIColor *color = [[UIColor greenColor] retain]; //line 1 //OR(You will have color variable either like line 1 or line 2) color = curView.backgroundColor;//line 2 CGColorRef colorRef = [color CGColor]; int _countComponents = CGColorGetNumberOfComponents(colorRef); if (_countComponents == 4) { const CGFloat *_components = CGColorGetComponents(colorRef); CGFloat red = _components[0]; CGFloat green = _components[1]; CGFloat blue = _components[2]; CGFloat alpha = _components[3]; NSLog(@"%f,%f,%f,%f",red,green,blue,alpha); } [color release];