Search code examples
objective-ccore-graphicsgradientuibezierpathcgrectmake

Core Graphics won't load all the way for certain buttons


I am coding a button background of a simple red gradient, which works when the height is less than 100, but will simply stop loading the gradient if the button is larger than that and I can't figure out why. I am using PaintCode (which up until now has worked like a charm) to draw the code, then I changed the size of the gradient from [UIBezierPath bezierPathWithRoundedRect: CGRectMake(0, 0, 240, 120) cornerRadius: 4]; to [UIBezierPath bezierPathWithRoundedRect: CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) cornerRadius: 4]; because the size of the button changes between 4.5" and 5" devices. I am using other gradients with identical codes minus the color on other buttons and they work perfectly fine. It is only when the height is greater than 100 pts that I find a problem. Any idea what's wrong?

Here is the code that I'm using:

//// General Declarations
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = UIGraphicsGetCurrentContext();

//// Color Declarations
UIColor* lightRedColor = [UIColor colorWithRed: 1 green: 0.188 blue: 0.098 alpha: 1];
UIColor* darkRedColor = [UIColor colorWithRed: 0.812 green: 0.016 blue: 0.016 alpha: 1];

//// Gradient Declarations
NSArray* redGradientColors = [NSArray arrayWithObjects:
                              (id)lightRedColor.CGColor,
                              (id)[UIColor colorWithRed: 0.906 green: 0.102 blue: 0.057 alpha: 1].CGColor,
                              (id)darkRedColor.CGColor, nil];
CGFloat redGradientLocations[] = {0, 0.5, 1};
CGGradientRef redGradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)redGradientColors, redGradientLocations);

//// Rounded Rectangle Drawing
UIBezierPath* roundedRectanglePath = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(0, 0,  self.frame.size.width, self.frame.size.height) cornerRadius: 4];
CGContextSaveGState(context);
[roundedRectanglePath addClip];
CGContextDrawLinearGradient(context, redGradient, CGPointMake(120, 0), CGPointMake(120, 120), 0);
CGContextRestoreGState(context);


//// Cleanup
CGGradientRelease(redGradient);
CGColorSpaceRelease(colorSpace);

Edit: here is a screenshot of the button:


Solution

  • CGContextDrawLinearGradient(context, redGradient, CGPointMake(120, 0), CGPointMake(120, 120), 0);

    Here you are specifying the height of the gradient area to draw, with an end point of y=120. This means your gradient will be 120 points high regardless of the code above it. Change the end point to be CGPointMake(120, self.bounds.size.height) and you should be fine.