【iOS】Set background gradient color

drawRect function

Mainly responsible for iOS drawing operations, the program will automatically call this method for drawing. I draw gradient background color in this function.

Method definition:

  • -(void)drawRect:(CGRect)rect;
    Override this method to perform redrawing tasks
  • -(void)setNeedsDisplay;
    Mark as needing redrawing, call drawRect asynchronously
  • -(void)setNeedsDisplayInRect:(CGRect)rect;
    marked as requiring partial redrawing

Calling mechanism:

  1. The system calls it automatically, after Controller->viewDidLoad. However, if the rect size is not set when UIView is initialized, drawRect will not be automatically called.
  2. Directly call setNeedsDisplay, or setNeedsDisplayInRect: to trigger drawRect:, but there is a prerequisite that rect cannot be 0.

drawing method

Draw using CALayer or CGGradientRef.

CALayer

Use CALayer's subclass CAGradientLayer to draw gradient background colors.

// 初始化
CAGradientLayer* layer = [[CAGradientLayer alloc] init];
    
// 颜色数组,设置需要过渡的颜色(CGColor对象)。
layer.colors = @[(__bridge id)[UIColor colorWithRed:0.439f green:0.522f blue:0.714f alpha:1].CGColor, (__bridge  id)[UIColor colorWithRed:0.529f green:0.655f blue:0.851f alpha:1].CGColor, (__bridge  id)[UIColor whiteColor].CGColor];
    
// 开始位置与结束位置。(0, 0)左上角,(1, 1)右下角
layer.startPoint = CGPointMake(0.5, 0);
layer.endPoint = CGPointMake(0.5, 1);

// layer大小
layer.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height / 3);
    
[self.layer addSublayer:layer];

exhibit:
Insert image description here

CGGradientRef

// 图形上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    // 颜色空间
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    // 创建颜色数组
    // 由于指定RGB颜色空间,四个数组元素代表一个颜色(r, g, b, alpha)
    CGFloat compoents[12] = {
    
    
        0.2, 0.2, 0.2, 1,
        0.4, 0.4, 0.4, 1,
        0.8, 0.8, 0.8, 1
    };
    
    // 渐变位置(0~1),数组元素个数不小于颜色数
    CGFloat locations[3] = {
    
    0, 0.4, 0.8};
    
    // 创建梯度上下文
    CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, compoents, locations, 3);
    
    // 绘制线性渐变
    /*
     startPoint与endPoint:起始于结束位置,需要位置坐标
     options:绘制方式
     kCGGradientDrawsBeforeStartLocation 开始位置之前就进行绘制,到结束位置之后不再绘制,
     kCGGradientDrawsAfterEndLocation 开始位置之前不进行绘制,到结束点之后继续填充
     */
    CGContextDrawLinearGradient(ctx, gradient, CGPointMake(self.frame.size.width/2, 0), CGPointMake(self.frame.size.width/2, self.frame.size.height/3), kCGGradientDrawsAfterEndLocation);
    
    // 释放颜色空间
    CGColorSpaceRelease(colorSpace);

exhibit:
Insert image description here

Guess you like

Origin blog.csdn.net/m0_63852285/article/details/129344971