【iOS】Establecer color de degradado de fondo

función dibujarRect

Principalmente responsable de las operaciones de dibujo de iOS, el programa llamará automáticamente a este método para dibujar. Dibujo un color de fondo degradado en esta función.

Definición del método:

  • -(void)drawRect:(CGRect)rect;
    Anula este método para realizar tareas de redibujado
  • -(void)setNeedsDisplay;
    marcar como necesario volver a dibujar, llamar a drawRect de forma asincrónica
  • -(void)setNeedsDisplayInRect:(CGRect)rect;
    marcado como que requiere un rediseño parcial

Mecanismo de llamada:

  1. El sistema lo llama automáticamente, después de Controlador->viewDidLoad. Sin embargo, si el tamaño rect no se establece cuando se inicializa UIView, no se llamará automáticamente a drawRect.
  2. Llame directamente a setNeedsDisplay o setNeedsDisplayInRect: para activar drawRect:, pero existe un requisito previo de que rect no puede ser 0.

metodo de dibujo

Dibuja usando CALayer o CGGradientRef.

CALayer

Utilice la subclase CAGradientLayer de CALayer para dibujar colores de fondo degradados.

// 初始化
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];

anexo:
Insertar descripción de la imagen aquí

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);

anexo:
Insertar descripción de la imagen aquí

Supongo que te gusta

Origin blog.csdn.net/m0_63852285/article/details/129344971
Recomendado
Clasificación