background Gradient : linear left to right in objective C

Harshit Goel picture Harshit Goel · Feb 27, 2017 · Viewed 13.4k times · Source

My client wants the background View with this gradient effect background Gradient : rgb(118,118,118) | #ffffff | rgb(198,198,197) linear left to right I have tried this way but it is happening in Vertical direction I want it in Horizontal way

UIColor *leftColor = [UIColor colorWithRed:118.0/255.0 green:118.0/255.0 blue:118.0/255.0 alpha:1.0];
UIColor *middleColor = [UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1.0];
UIColor *rightColor = [UIColor colorWithRed:198.0/255.0 green:198.0/255.0 blue:197.0/255.0 alpha:1.0];

// Create the gradient
CAGradientLayer *theViewGradient = [CAGradientLayer layer];
theViewGradient.colors = [NSArray arrayWithObjects: (id)leftColor.CGColor, (id)middleColor.CGColor,(id)rightColor.CGColor, nil];
theViewGradient.frame = self.view.bounds;
//Add gradient to view
[self.view.layer insertSublayer:theViewGradient atIndex:0];

Like this ?? enter image description here

Answer

Ocunidee picture Ocunidee · Feb 27, 2017

You need to set the startPoint and endPoint property of your gradientLayer. They represent the start coordinates of your first color and the coordinates of the end of your last color.

They are both CGPoints and their x and y should have values between 0.0 et 1.0.

By default the startPoint has these coordinates (0.5, 0.0), while the endPoint has those (0.5, 1.0).

(0.0, 0.0) is the top left corner while (1.0, 1.0) is the bottom right corner

so try:

theViewGradient.startPoint = CGPointMake(0.0, 0.5);
theViewGradient.endPoint = CGPointMake(1.0, 0.5);