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?
#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.
You'll want to use CGGradient. See the iPhone Dev Center "CGGradient Reference" document.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With