Kex
Kex

Reputation: 8589

Core Graphics and arrays

I am drawing a gradient in core graphics like so:

- (void)drawRect:(CGRect)rect {

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); //Standard color space we will use

    NSArray *colorsArray = [NSArray arrayWithObjects:(__bridge id)self.startColor.CGColor, (__bridge id)self.endColor.CGColor, nil];

    //Why is this array created like this?
    CGFloat colorLocations[] = {0.0, 1.0};

    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)colorsArray, colorLocations);

    CGPoint startPoint = CGPointZero;
    CGPoint endPoint = CGPointMake(0, self.bounds.size.height);

    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);



}

I know that we are dealing with a lower level API here an c functions. I'm not sure what the differences are between CFArrayRef and CFArray, is this just how pointers work in c or is it related to the Core Foundation framework?

I understand that we use __bridge to cast from objective c to core foundation, however why is the colorLocations array declared like this:

CGFloat colorLocations[] = {0.0, 1.0};

and not as a standard NSArray? Any tips on this would be really appreciated. Thanks!!

Upvotes: 1

Views: 70

Answers (1)

Amin Negm-Awad
Amin Negm-Awad

Reputation: 16650

The declaration …

CGFloat colorLocations[] = {0.0, 1.0};

declares a C array. The benefit is that C arrays are faster by far, if you access it: There is no method dispatch, no bounds checking, no capability of insertion and removal …

But they are incredible fast, when you access them. (In most cases is a simple pointer addition a modern CPU can do with an internal address calculation unit.)

Since drawing code has to be fast in the past and you can have very big arrays for drawing, they decided to do that with a C array.

Upvotes: 1

Related Questions