• CALayer创建图层(转)


    一.添加一个图层 
      添加图层的步骤: 
      1.创建layer 
      2.设置layer的属性(设置了颜色,bounds才能显示出来) 
      3.将layer添加到界面上(控制器view的layer上)

    @interface ViewController ()
    
    @property(nonatomic,strong) UIView *customView;
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        /** 1.创建一个layer **/
        //使用对象方法创建
        //CALayer *layer = [[CALayer alloc] init];
        //使用类方法创建
        CALayer *layer = [CALayer layer];
    
        /** 2.设置layer的属性 **/
        layer.backgroundColor = [UIColor brownColor].CGColor;
        layer.bounds = CGRectMake(0,
                                  0,
                                  100,
                                  100);
        layer.position = CGPointMake(100, 100);
    
        /**  3.把layer添加到界面上 **/
        [self.view.layer addSublayer:layer];
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
    }
    
    @end

    二.添加一个显示图片的图层

    @interface ViewController ()
    @property(nonatomic,strong) UIView *customView;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        //创建一个layer
        CALayer *layer = [CALayer layer];
        //设置layer的属性
        layer.bounds = CGRectMake(100,100,100,100);
        layer.position = CGPointMake(100, 100);
        //设置需要显示的图片
        layer.contents = (id)[UIImage imageNamed:@"logo.jpg"].CGImage;
        //设置圆角半径为10
        layer.cornerRadius = 10;
        //如果设置了图片,那么需要设置这个属性YES才能显示圆角效果
        layer.masksToBounds = YES;
        //设置边框
        layer.borderWidth = 3;
        layer.borderColor = [UIColor brownColor].CGColor;
        [self.view.layer addSublayer:layer];
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
    }
    
    @end

    三.CGColorRef和CGImageRef数据类型 
      简单说明CALayer是定义在QuartzCore框架中的。CGImageRef, CGColorRef两种数据类型是定义在CoreGraphics框架中的。UIColor,UIImage是定义在UIKit框架中的。 
    其次,QuartzCore框架和CoreGraphics框架是可以跨平台使用的,在iOS和Mac OS X上都能使用,但是UIKit只能在iOS中使用。 
    因此,为了保证可移植性,QuartzCore不能使用UIImage,UIColor,只能使用CGImageRef,CGColorRef。 
    不过很多情况下,可以通过UIKit对象的特定方法,得到CoreGraphics对象,比如UIImage的CGImage方法可以返回一个CGImageRef。

    四.UIView和CALayer的选择 
      可以发现,前面的2个效果不仅可以通过添加层来实现,还可以通过添加UIView来实现。既然CALayer和UIView都能实现相同的显示效果,那究竟该选择谁好呢? 
    其次,对比CALayer,UIView多了一个事件处理的功能。也就是说,CALayer不能处理用户的触摸事件,而UIView可以。 
    所以,在选择的过程中,需要考虑到实际的情况,如果显示出来的东西需要跟用户进行交互的话,用UIView;如果不需要跟用户进行交互,用UIView或者CALayer都可以。 
    当然,CALayer的性能会高一些,因为它少了事件处理的能力,更加轻量级。

  • 相关阅读:
    Sqoop学习笔记_Sqoop的基本使用一
    hive报错( Non-Partition column appears in the partition specification)
    【python-leetcode112-树的深度遍历】路径总和
    谷歌colab运行paddlepaddle之手写数字识别
    谷歌colab上安装百度paddlepaddle框架
    谷歌colab查看cuda的版本
    深度学习数学知识之概率论
    深度学习数学知识之线性代数
    深度学习数学知识之高等数学
    【python-leetcode113-树的深度遍历】路径总和Ⅱ
  • 原文地址:https://www.cnblogs.com/jiuyi/p/10103739.html
Copyright © 2020-2023  润新知