How to do the reverse color of specific UIColor in objective-c

0 votes
124 views
asked May 21, 2015 by jonathan (3,105 points)
Hi All

   How to do the reverse color of specific UIColor in objective-c?

1 Answer

0 votes
answered May 21, 2015 by kalpana (3,995 points)
Hi

  Try this code it ll do the magic..

-(UIColor *)reverseColorOf :(UIColor *)oldColor

{

    CGColorRef oldCGColor = oldColor.CGColor;

    

    int numberOfComponents = CGColorGetNumberOfComponents(oldCGColor);

    // can not invert - the only component is the alpha

    if (numberOfComponents == 1) {

        return [UIColor colorWithCGColor:oldCGColor];

    }

    

    const CGFloat *oldComponentColors = CGColorGetComponents(oldCGColor);

    CGFloat newComponentColors[numberOfComponents];

    

    int i = numberOfComponents - 1;

    newComponentColors[i] = oldComponentColors[i]; // alpha

    while (--i >= 0) {

        newComponentColors[i] = 1 - oldComponentColors[i];

    }

    

    CGColorRef newCGColor = CGColorCreate(CGColorGetColorSpace(oldCGColor), newComponentColors);

    UIColor *newColor = [UIColor colorWithCGColor:newCGColor];

    CGColorRelease(newCGColor);

    

    //=====For the GRAY colors 'Middle level colors'

    CGFloat white = 0;

    [oldColor getWhite:&white alpha:nil];

    

    if(white>0.3 && white < 0.67)

    {

        if(white >= 0.5)

            newColor = [UIColor darkGrayColor];

        else if (white < 0.5)

            newColor = [UIColor blackColor];

        

    }

    return newColor;

}
...