CAGradientLayer 获取像素颜色

Posted

技术标签:

【中文标题】CAGradientLayer 获取像素颜色【英文标题】:CAGradientLayer get color at pixel 【发布时间】:2015-12-12 15:46:36 【问题描述】:

我有一个带有许多颜色停止点的CAGradientLayer。假设我知道所选图层上的点。如何获取该位置的像素颜色?

我正在尝试在渐变上选择一个位置,但我不确定如何在其边界的特定点获取图层的像素颜色。

【问题讨论】:

你看过***.com/a/8354632/2442804吗? @luk2302 我得到红色:1 绿色:1,蓝色:1,alpha:1。我想知道这是否与它是渐变层有关。 嗯,不知道,我希望这不会有关系,因为你告诉它把自己渲染到上下文中......今天晚些时候我会检查一下。 【参考方案1】:

查看我的示例,它根据我的 UISlider 位置值 0

-(UIColor *) getColor

/*      //My pre declared code(just for clarity)
        @property (weak, nonatomic) IBOutlet UISlider *slider;
        CAGradientLayer*  gradientLayer;
        float colorCutoff;


        gradientLayer.colors = @[(__bridge id)[UIColor redColor].CGColor,(__bridge id)[UIColor orangeColor].CGColor,(__bridge id)[UIColor yellowColor].CGColor,(__bridge id)[UIColor  greenColor].CGColor,
        (__bridge id)[UIColor cyanColor].CGColor,(__bridge id)[UIColor blueColor].CGColor,(__bridge id)[UIColor purpleColor].CGColor];

        //This below allows for easy one direction interpolation
        gradientLayer.startPoint = CGPointMake(0.5,0.0);
        gradientLayer.endPoint = CGPointMake(0.5,1.0f);
        colorCutoff = 1/gradientLayer.colors.count;

 *
 *
 */
float interp  = _slider.value;
// 1.0f * colors.count == index out of bounds
if(interp >= 1.0f)
    interp = .99999f;


// think FLOOR(float * float)
int firstColor = (interp * (float)gradientLayer.colors.count);
int secondColor = firstColor +1;


// In case we are at the last color their is not one above it(index out of bounds)
if(secondColor >= gradientLayer.colors.count)
    firstColor--;
    secondColor--;


// In My case the closer you are to the colorCuttoff the more the second color should have a factor
// 0 is red .14 is orange .28 is yellow and soo on
float firstInterp = 1.0f - (fmodf(interp,colorCutoff) / colorCutoff);
float secondInterp = 1.0f - firstInterp;

// make use of the gradientLayer.colors array
const CGFloat *firstCGColor = CGColorGetComponents((__bridge CGColorRef)gradientLayer.colors[firstColor]);
const CGFloat *secondCGColor = CGColorGetComponents((__bridge CGColorRef)gradientLayer.colors[secondColor]);

float red = (firstCGColor[0] * firstInterp) + secondCGColor[0] * secondInterp;
float green = (firstCGColor[1] * firstInterp) + secondCGColor[1] * secondInterp;
float blue  = (firstCGColor[2] * firstInterp) + secondCGColor[2] * secondInterp;
return [UIColor colorWithRed:red green:green blue:blue alpha:1.0f]; 

【讨论】:

以上是关于CAGradientLayer 获取像素颜色的主要内容,如果未能解决你的问题,请参考以下文章

CAGradientLayer 颜色更改动画未执行

CAGradientLayer颜色渐变器

如何像屏幕保护程序一样更改 CAGradientLayer 的颜色?

颜色线性渐变-CAGradientLayer

使用滑块实时更改 CAGradientLayer 的颜色

在两个 CAGradientLayer 颜色设置之间连续渐变?