iOS 中 CGRectInset & CGRectOffset

CGRectInset

CGRect CGRectInset(CGRect rect, CGFloat dx, CGFloat dy)
表示在 rect 的基础上,分别在 x 和 y 方向上进行缩放:

  1. dx > 0, 在 x 方向上缩小 2 dx; dx < 0, 在 x 方向上放大 2 (-dx);

  2. dy > 0, 在 y 方向上缩小 2 dy; dy < 0, 在 y 方向上放大 2 (-dy);

1
2
3
4
5
6
7
8
UIView * view1 = [[UIView    alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
view1.backgroundColor = [UIColor redColor];
[self.view addSubview:view1];

UIView * view2 = [UIView new];
view2.frame = CGRectInset(view1.frame, 10, 10);
view2.backgroundColor = [UIColor blackColor];
[self.view addSubview:view2];

如下图:

CGRectOffset

CGRect CGRectOffset(CGRect rect, CGFloat dx, CGFloat dy) 表示以 rect 的 origin 为基点在 x 和 y 方向进行偏移:

  1. dx > 0, 在 x 方向上向右偏移 dx; dx < 0, 在 x 方向上向左偏移 -dx;
  2. dy > 0, 在 y 方向上向下偏移 dy; dy < 0, 在 y 方向上向上偏移 -dy;
1
2
3
4
5
6
7
8
UIView * view1 = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
view1.backgroundColor = [UIColor redColor];
[self.view addSubview:view1];

UIView * view2 = [UIView new];
view2.frame = CGRectOffset(view1.frame, -20, 20);
view2.backgroundColor = [UIColor blackColor];
[self.view addSubview:view2];

如下图: