iOS开发笔记——frame与bouns详解

2018-12-03  本文已影响0人  勤奋的小卫子

1.iOS坐标系

iOS坐标系中,以屏幕左上角为坐标原点,往右是X正方向,往下是Y正方向

iOS坐标系

boundsframe都是属于CGRect类型的结构体,包含一个CGPoint(起点)和一个CGSize(尺寸)子结构体。

struct CGRect{
        CGPoint origin;
        CGSize size;
};

origin决定view的起点,size决定view的尺寸

2.frame

frame表示view在父view坐标系统中的位置和大小,参考坐标是父视图的坐标系统。
代码示例:

    UIView *viewA = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 200, 200)];
    [viewA setBackgroundColor:[UIColor blueColor]];
    [self.view addSubview:viewA];
    
    UIView *viewB = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];
    [viewB setBackgroundColor:[UIColor yellowColor]];
    [viewA addSubview:viewB];
    
    UIView *viewC = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 50, 50)];
    [viewC setBackgroundColor:[UIColor redColor]];
    [self.view addSubview:viewC];

运行效果:


图一

小结:
viewBviewC起点重合,viewB的起点为 (50,50),而viewC的起点为(100,100)。原因是frame中的位置以父坐标为标准来确定当前视图位置,viewB的视图为viewAviewC的视图为self.view,而viewA的起点为(50,50),因此viewCviewB起点才会重合。

3.bounds

这个属性一般不进行设置,表示view在本地坐标系统中的位置和大小,参考点是本地坐标系统,而本地坐标系统原点默认为(0,0)
每个视图都有自己的坐标系,且坐标系默认以自身左上角为坐标原点,所有子视图都以这个坐标系原点为基准点。

4.两者区别

直接上源码

-(CGRect)frame{
    return CGRectMake(self.frame.origin.x,self.frame.origin.y,self.frame.size.width,self.frame.size.height);
}
-(CGRect)bounds{
    return CGRectMake(0,0,self.frame.size.width,self.frame.size.height);
}

4.1 origin区别

可以很明显看·origin不同,frameorigin是不定的,而bounds(0,0),在不修改bounds情况下。

4.2 size区别

framesize直接决定view大小,而boundssize修改后,view中心点不变,长宽以中心点为基准缩放。
代码示例:

UIView *viewA = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 240)];
    [viewA setBackgroundColor:[UIColor blueColor]];
    [self.view addSubview:viewA];
    
    UIView *viewB = [[UIView alloc] initWithFrame:CGRectMake(100, 50, 160, 120)];
    [viewB setBackgroundColor:[UIColor redColor]];
    [viewA addSubview:viewB];
    
    //viewB设置size(320,160)
    [viewB setBounds:CGRectMake(0, 0, 200, 160)];

运行效果:


更改bounds前 更改bounds后

5.总结

上一篇 下一篇

猜你喜欢

热点阅读