Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically create a UIView with color gradient

I'm trying to generate a view with a gradient color background (A solid color to transparent) at runtime. Is there a way of doing that?

like image 660
Allan Jiang Avatar asked Apr 15 '14 04:04

Allan Jiang


Video Answer


1 Answers

Objective-C:

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)]; CAGradientLayer *gradient = [CAGradientLayer layer];  gradient.frame = view.bounds; gradient.colors = @[(id)[UIColor whiteColor].CGColor, (id)[UIColor blackColor].CGColor];  [view.layer insertSublayer:gradient atIndex:0]; 

Swift:

let view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 50)) let gradient = CAGradientLayer()  gradient.frame = view.bounds gradient.colors = [UIColor.white.cgColor, UIColor.black.cgColor]  view.layer.insertSublayer(gradient, at: 0) 

Info: use startPoint and endPoint to change direction of gradient.

If there are any other views added onto this UIView (such as a UILabel), you may want to consider setting the background color of those UIView’s to [UIColor clearColor] so the gradient view is presented instead of the background color for sub views. Using clearColor has a slight performance hit.

like image 128
Arslan Ali Avatar answered Oct 06 '22 11:10

Arslan Ali