【问题标题】:get components of color in objective-c在objective-c中获取颜色分量
【发布时间】:2012-02-21 19:22:09
【问题描述】:

这里是一个用于获取颜色的 RGB 分量的代码 sn-ps。如果 _countComponents 小于四个,例如两个,我该怎么办?我试图获取颜色灰色 [UIColor grayColor]

的组件
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];

【问题讨论】:

  • 你的意思是:"我试图获取颜色为灰色的组件 [UIColor grayColor]"

标签: objective-c components uicolor


【解决方案1】:

如果你有一个 UIColor 实例并且你想要它的 RGB 值,为什么不使用-getRed:green:blue:alpha: 方法?

CGFloat r, g, b, a;
BOOL success = [myColor getRed:&r green:&g blue:&b alpha:&a];
if (success) {
    // the color was converted to RGB successfully, go ahead and use r,g,b, and a.
}

【讨论】:

    【解决方案2】:

    颜色的组成部分取决于关联的color space

    所以_components[0]_components[1] 等不需要红色、绿色、蓝色和 alpha。

    【讨论】:

      【解决方案3】:

      新答案

      重新阅读问题后。要回答灰色组件问题,您阅读的方式是通过 -(BOOL)getWhite:alpha:

      因此,您可以按照 Caleb 的方式执行以下操作:

      BOOL success = [myColor getWhite:&w alpha:&a];
      

      这为您提供了灰度值 w 为 0 到 1 和 alpha 值 a 为 0 到 1

      请参阅 Apple 文档 getWhite:alpha:

      旧答案

      来自这个 SO 问题how-to-access-the-color-components-of-an-uicolor

      查看(相当老的)ArsTechnica 文章 iphone-development-accessing-uicolor-components

      【讨论】:

      • +1 别再看问题了——你让我们其他人看起来很傻。
      猜你喜欢
      • 1970-01-01
      • 2015-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多