iOS核心动画高级技巧二

  • 基础视图
UIView *layerView = [[UIView alloc] initWithFrame:CGRectMake(100.0f, 100.0f, 200.0f, 200.0f)];
layerView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:layerView];
复制代码
  • 显示图片
UIImage *image = [UIImage imageNamed:@"test.jpg"];
layerView.layer.contents = (__bridge id _Nullable)(image.CGImage);
复制代码

Simulator Screen Shot - iPhone 8 - 2021-05-29 at 10.37.06.png

  • 等比例拉伸以适应图层的边界
layerView.layer.contentsGravity = kCAGravityResizeAspect; 
复制代码

Simulator Screen Shot - iPhone 8 - 2021-05-29 at 10.39.11.png

  • contentsScale
layerView.layer.contentsGravity = kCAGravityCenter;
layerView.layer.contentsScale = [[UIScreen mainScreen] scale];
复制代码

Simulator Screen Shot - iPhone 8 - 2021-05-29 at 10.41.35.png

  • masksToBounds
layerView.layer.masksToBounds = YES;
复制代码

Simulator Screen Shot - iPhone 8 - 2021-05-29 at 10.43.29.png

  • contentsRect 相当于裁剪显示区域(下图显示为整个图片的左上方部分图片)
layerView.layer.contentsRect = CGRectMake(0.0f, 0.0f, 0.5f, 0.5f);
复制代码

Simulator Screen Shot - iPhone 8 - 2021-05-29 at 10.46.01.png

Simulator Screen Shot - iPhone 8 - 2021-05-29 at 10.46.12.png

  • contentsCenter
layerView.layer.contentsCenter = CGRectMake(0.25, 0.25, 0.5, 0.5);
复制代码

Simulator Screen Shot - iPhone 8 - 2021-05-29 at 10.53.25.png

  • 绘图
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];
复制代码
  • CALayerDelegate
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
    CGContextSetLineWidth(ctx, 10.0f);
    CGContextSetStrokeColorWithColor(ctx, [UIColor redColor].CGColor);
    CGContextStrokeEllipseInRect(ctx, layer.bounds);
}
复制代码

Simulator Screen Shot - iPhone 8 - 2021-05-29 at 11.00.24.png

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享