CAGradientLayer获取像素颜色

时间:2015-12-12 15:46:37

标签: ios swift gradient cagradientlayer

我有一个CAGradientLayer有很多色点。假设我知道所选图层上的点。如何在该位置获得像素颜色?

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

1 个答案:

答案 0 :(得分:0)

查看我的示例,它根据我的UISliders位置值0< = slider.value< = 1.0f来插入颜色。如果您的CAGradientLayer的起点和终点不同,则必须更改映射的工作方式。我认为对于标准的起点和终点,渐变从左上角到右下角,在这种情况下,如果您将图层视为颜色条纹对角线的矩形,您需要做的就是将矩形旋转45度然后只使用x或y位置(取决于你如何旋转),这应该允许你使用这种方法。

-(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]; 
}