Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually drawing a gradient in iPhone apps?

If I have two UIColors, what's the best way to draw an even gradient between them over an arbitrarily-sized area?

I am guessing you would create a UIView subclass and use the CG drawing methods in the drawRect method. I just don't know which ones, or if there are any pitfalls to watch out for, like performance. Has anyone done this?

like image 705
Mike McMaster Avatar asked Oct 22 '08 18:10

Mike McMaster


3 Answers

#import <QuartzCore/QuartzCore.h>    
- (void) setGradient {
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = self.view.bounds;
    gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor whiteColor] CGColor], (id)[[UIColor blackColor] CGColor], nil];
    [self.view.layer insertSublayer:gradient atIndex:0];     
}

Don't forget to add QuartzCore library to your project.

like image 72
Anton Chikin Avatar answered Oct 26 '22 10:10

Anton Chikin


You'll want to use CGGradient. See the iPhone Dev Center "CGGradient Reference" document.

like image 40
Ben Gottlieb Avatar answered Oct 26 '22 10:10

Ben Gottlieb


The Swift way to add Gradient is :

    var view : UIView = UIView(frame: CGRectMake(0, 0, 320, 100))
    var g : CAGradientLayer = CAGradientLayer()
    g.frame = gradientView.bounds
    g.colors = ["000000".UIColor.CGColor , "111111".UIColor.CGColor]
    view.layer.insertSublayer(g, atIndex: 0)

UIColor() is a helper class for Swift to convert hex color to rgb color, highly recommended.

like image 28
Reza_Rg Avatar answered Oct 26 '22 11:10

Reza_Rg