0

I would like to create a color gradient with CAGradientLayer for multiple views with different sizes. I don't know how to define the frame separately:

UIColor *darkOp = [UIColor colorWithRed:0.2f green:0.2f blue:0.27f alpha:1.0];
UIColor *lightOp = [UIColor colorWithRed:0.36f green:0.35f blue:0.42f alpha:1.0];

// Create the gradient
CAGradientLayer *gradient = [CAGradientLayer layer];

// Set colors
gradient.colors = [NSArray arrayWithObjects:
                   (id)darkOp.CGColor,
                   (id)lightOp.CGColor,
                   nil];
//set radius
gradient.cornerRadius = 5.0;

// Set bounds BUT just for one view size
gradient.frame = self.numberRegionView.bounds; //<-- here I can just define one frame size

// Add the gradient to one view
[self.numberRegionView.layer insertSublayer:gradient atIndex:0];

//but how to add the gradient layer to views with different sizes ???
//[self.graphRegionView.layer insertSublayer:gradient atIndex:0]; ???
//[self.barRegionView.layer insertSublayer:gradient atIndex:0];   ???

Thanks!

JFS
  • 2,992
  • 3
  • 37
  • 48
  • Why not create a new gradient layer for each new view/size? I'm not sure about re-using a CAGradientLayer. – Putz1103 Jan 23 '14 at 21:44
  • Thanks Putz, that would definitely work but I hoped to find a solution which could avoid repeating the same code multiple times. – JFS Jan 23 '14 at 21:49
  • I'll post some code as an answer to show it's not really repeating code. Use it as you wish. – Putz1103 Jan 23 '14 at 21:53

1 Answers1

1
-(void)setGradientForView:(UIView*)view
{
    static UIColor *darkOp = [UIColor colorWithRed:0.2f green:0.2f blue:0.27f alpha:1.0];
    static UIColor *lightOp = [UIColor colorWithRed:0.36f green:0.35f blue:0.42f alpha:1.0];

    // Create the gradient
    CAGradientLayer *gradient = [CAGradientLayer layer];

    // Set colors
    gradient.colors = [NSArray arrayWithObjects:
                   (id)darkOp.CGColor,
                   (id)lightOp.CGColor,
                   nil];
    //set radius
    gradient.cornerRadius = 5.0;

    // Set bounds BUT just for one view size
    gradient.frame = view.bounds; //<-- here I can just define one frame size

    // Add the gradient to one view
    [view.layer insertSublayer:gradient atIndex:0];
}

Then use this code for your three views:

[self setGradientForView:self.numberRegionView];
[self setGradientForView:self.barRegionView];
[self setGradientForView:self.numberRegionView];
Putz1103
  • 6,211
  • 1
  • 18
  • 25
  • But view in view.bounds is an undeclared identifier now. – JFS Jan 23 '14 at 22:01
  • I like that. Thank you very much. The gradient view size is not updating for the bigger screen size. Any idea? Thanks anyway! – JFS Jan 23 '14 at 22:08