CoreGraphics para renderizado a nivel de píxel de alto rendimiento

Actualizar cuadro por cuadro con CADisplayLink

CADisplayLink* displayLink = [CADisplayLink displayLinkWithTarget: self 
                                                         selector: @selector(update)];
[displayLink addToRunLoop: NSRunLoop.mainRunLoop 
                  forMode: NSDefaultRunLoopMode];

En el método de actualización, llama a setNeedsDisplay de la UIView renderizada

- (void)update {
    [self.vv setNeedsDisplay];
}

Bajo la subclase UIView renderizada, herede drawLayer

// drawRect 也记得写上,否则失效
- (void)drawRect:(CGRect)rect {
    [super drawRect: rect];
}

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
    CGContextClearRect(ctx, CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height));
    CGContextSaveGState(ctx);
    const int width = 320;
    const int height = 640;
    CGRect drawRect = CGRectMake(0, 0, width, height);
    CGContextTranslateCTM(ctx, 0, self.bounds.size.height);
    CGContextScaleCTM(ctx, self.bounds.size.width / width, -self.bounds.size.height / height); 
    uint32_t pixels[width * height] = { 0 };
    for (size_t i = 0; i < width * height; ++i) {
        pixels[height][width] = 0xffffffff;
    }
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pixels,
                                                 width,
                                                 height,
                                                 8,
                                                 width * 4,
                                                 colorSpace,
                                                 kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little);
    CGColorSpaceRelease(colorSpace);
    CGImageRef imageRef = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    CGContextDrawImage(ctx, drawRect, imageRef);
    CGContextRestoreGState(ctx);
}

○ Recuerda heredar drawRect

Cuando dibujamos CALayer, necesitamos usar la información relevante de UIView, que se almacena en CGContextRef, y esta información solo se puede usar drawRectdespués de .

Es decir, después de que UIView llame a drawRect, también llamará a drawLayer. Por lo tanto, al heredar UIView, debe heredar e implementar drawRect, para que se llame a la herencia de drawLayer.

○ CGContextClearRect

Se utiliza para borrar la información dibujada en el rectángulo.

○ CGContextSaveGState/CGContextRestoreGState

Guarde y restaure el contexto, llamado al principio y al final del dibujo de una capa. para evitar romper el contexto anterior.

○ CGContextTranslateCTM

La función de esta función es traducir el contexto del dibujo a lo largo del eje x y el eje y por la distancia especificada.

En este ejemplo, ¿por qué CGContextTranslateCTM se llama así?

`CGContextTranslateCTM(ctx, 0, self.bounds.size.height);` 

Esto solo CGContextScaleCTMpuede .

CGContextTranslateCTM se usa para establecer el área de inicio del dibujo de la pantalla, que se usa aquí (0, self.bounds.size.height)para establecer el área de inicio del dibujo en la parte inferior izquierda de la pantalla.

○ CGContextScaleCTM

Si sigue la configuración de la línea de código anterior, el área dibujada obviamente está "fuera de la pantalla". Entonces se necesita una segunda función CGContextScaleCTM, y puedes ver que la función se llama así:

CGContextScaleCTM(ctx, self.bounds.size.width / width, -self.bounds.size.height / height); 

Se puede ver que esta función se usa para estirar la pantalla. La relación de estiramiento se estira completamente horizontal y verticalmente. Esto es fácil de entender, pero el punto clave es prestar atención al segundo parámetro:

-self.bounds.size.height / height

El segundo parámetro es un valor negativo, lo que significa que el área dibujada se estirará al revés, por lo que la imagen se volteará.Después de combinar CGContextTranslateCTM, el dibujo de la imagen se convierte en la esquina inferior izquierda de la pantalla como la dirección inicial de las coordenadas verticales, dibujando en la esquina superior izquierda de la pantalla.

○ CGColorSpaceCreateDeviceRGB/CGColorSpaceRelease

Se utiliza para crear y liberar objetos de espacio de color RGB. El objeto creado se CGBitmapContextCreateutilizará .

○ CGBitmapContextCreate/CGContextRelease

La función de contexto de gráficos utilizada para crear y liberar el mapa de bits, a través del cual se pasan los datos del mapa de bits.

○ CGBitmapContextCrearImagen

Crea un mapa de bits.
Cabe señalar que no es necesario liberar el mapa de bits aquí, porque la referencia se usará para dibujar UIView y luego ingresará a la gestión del ciclo de vida de UIView.

○ CGContextDrawImagen

Una capa que representa un mapa de bits en una UIView.

Supongo que te gusta

Origin blog.csdn.net/madaxin/article/details/130337056
Recomendado
Clasificación