CGRectInset 和 CGRectOffset

727 阅读1分钟

CGRectInset

官方文档

image.png

CGRectInset(CGRect rect, CGFloat dx, CGFloat dy)

  • 第一个参数:待操作的CGRect
  • 第二个参数:水平方向平移的距离
    • 若为正数,向右平移
    • 若为负数,向左平移
  • 第三个参数:垂直方向平移的距离
    • 若为正数,向下平移
    • 若为负数,向上平移 所以可以理解为,正数是缩小,负数是放大

测试

UIView *pinkView = [[UIView alloc] initWithFrame:CGRectMake(2060200200)];
pinkView.backgroundColor = [UIColor systemPinkColor];
[self.view addSubview:pinkView];
​
//通过对pinkView的frame进行改变,来设置greenView的frame
UIView *greenView = [[UIView alloc] initWithFrame:CGRectInset(pinkView.frame, 4040)];
greenView.backgroundColor = [UIColor greenColor];
[self.view addSubview:greenView];

其实就是绿色矩形是相对于粉色矩形的frame,然后缩小40,效果如下

image.png

如果你是希望是相对于原来的放大,就设置一个负值(也就是官方文档的To create a larger, encompassing rectangle, specify a negative value.)

但是这样的话就会遮挡原来的粉色矩形了,效果如下

image.png

CGRectOffest

官方文档

image.png

CGRectOffset(CGRect rect, CGFloat dx, CGFloat dy)

  • 与CGRectInset类似,但它是偏移量

测试

UIView *pinkView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
pinkView.backgroundColor = [UIColor systemPinkColor];
[self.view addSubview:pinkView];

//通过对pinkView的frame进行改变,来设置greenView的frame,是向右向下偏移40 (坐标)
UIView *greenView = [[UIView alloc] initWithFrame:CGRectOffset(pinkView.frame, 40, 40)];
greenView.backgroundColor = [UIColor greenColor];
[self.view addSubview:greenView];

效果如下

image.png