• Based on the view
UIView *layerView = [[UIView alloc] initWithFrame:CGRectMake(100.0f, 100.0f, 200.0f, 200.0f)];
layerView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:layerView];
Copy the code
  • Display images
UIImage *image = [UIImage imageNamed:@"test.jpg"];
layerView.layer.contents = (__bridge id _Nullable)(image.CGImage);
Copy the code

  • Stretch evenly to fit the boundaries of the layers
layerView.layer.contentsGravity = kCAGravityResizeAspect; 
Copy the code

  • contentsScale
layerView.layer.contentsGravity = kCAGravityCenter;
layerView.layer.contentsScale = [[UIScreen mainScreen] scale];
Copy the code

  • masksToBounds
layerView.layer.masksToBounds = YES;
Copy the code

  • ContentsRect is equivalent to clipping the display area (the image below shows the upper left part of the entire image)
LayerView. Layer. ContentsRect = CGRectMake (0.0 f to 0.0 f to 0.5 f to 0.5 f);Copy the code

  • contentsCenter
LayerView. Layer. ContentsCenter = CGRectMake (0.25, 0.25, 0.5, 0.5);Copy the code

  • drawing
UIView *layerView = [[UIView alloc] initWithFrame:CGRectMake(100.0f, 100.0f, 200.0f, 200.0f)]; layerView.backgroundColor = [UIColor whiteColor]; [self.view addSubview:layerView]; CALayer *blueLayer = [CALayer layer]; Bluelayer. frame = CGRectMake(50.0f, 50.0f, 100.0f, 100.0f); blueLayer.backgroundColor = [UIColor blueColor].CGColor; [layerView.layer addSublayer:blueLayer]; blueLayer.delegate = self; [blueLayer display];Copy the code
  • CALayerDelegate
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
    CGContextSetLineWidth(ctx, 10.0f);
    CGContextSetStrokeColorWithColor(ctx, [UIColor redColor].CGColor);
    CGContextStrokeEllipseInRect(ctx, layer.bounds);
}
Copy the code