iOS CGRectInset的使用方法

CGRectInset CGRect CGRectInset (
CGRect rect,
CGFloat dx,
CGFloat dy
);

该结构体的应用是以原rect为中心,再参考dx,dy,进行缩放或者放大。

下面通过示例进行说明:

OC示例:

  - (void)demoTest {
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
    view1.backgroundColor = [UIColor redColor];
    [self.view addSubview:view1];
    NSLog(@"111=%@", NSStringFromCGRect(view1.frame));
    // 111={{100, 100}, {200, 200}}
    
    CGRect rect = CGRectInset(view1.frame, 30, 30);
    UIView *view2 = [[UIView alloc] initWithFrame:rect];
    view2.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:view2];
    NSLog(@"222=%@", NSStringFromCGRect(view2.frame));
    // {{130, 130}, {140, 140}}
}
  • 运行结果:


    屏幕快照 2016-12-02 下午1.58.22.png
  • 控制台打印可以看出,view1的frame值为111={{100, 100}, {200, 200}};view2的frame值为222={{130, 130}, {140, 140}}。

swift的示例:

func demoTest() {
         let view1 = UIView(frame:CGRect(x: 100, y: 100, width: 200, height: 200))
        view1.backgroundColor = #colorLiteral(red: 0.8549019694, green: 0.250980407, blue: 0.4784313738, alpha: 1)
        view.addSubview(view1)
        print(view1.frame)  // (100.0, 100.0, 200.0, 200.0)
        
        let rect = view1.frame.insetBy(dx: 30, dy: 30)
        let view2 = UIView(frame: rect)
        view2.backgroundColor = #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1)
        view.addSubview(view2)
        print(view2) // frame = (130 130; 140 140)
    }
  • 运行结果:


    屏幕快照 2016-12-02 下午2.04.38.png
  • 控制台输入view1的frame值为 (100.0, 100.0, 200.0, 200.0),view2的frame值为(130 130; 140 140).

你可能感兴趣的:(iOS CGRectInset的使用方法)