iOS开发-属性含义与用法iOS DeveloperiOS点点滴滴

iOS小知识(一):CGRectInset与CGRectOffs

2018-01-25  本文已影响35人  里克尔梅西

CGRectInset 与 CGRectOffset 都是通过参数改变CGRect并返回一个CGRect类型的数据。总结出两者的区别在于:CGRectInset会进行平移和缩放两个操作,CGRectOffset做的只是平移。

  1. CGRect CGRectOffset(CGRect rect, CGFloat dx, CGFloat dy)

通过第二个参数 dx 和第三个参数 dy 重置第一个参数 rect 作为结果返回。重置的方式为,首先将 rect 的坐标(origin)按照(dx,dy) 进行平移,然后将 rect 的大小(size) 宽度缩小2倍的 dx,高度缩小2倍的 dy。即如果dx、dy为正,则移动后缩小;若为负,则移动后扩大。

  1. CGRect CGRectOffset(CGRect rect, CGFloat dx, CGFloat dy)

只进行平移操作。

可以用下面的例子来实际运行观察。

- (void)testCGRectInset {
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
    [view1 setBackgroundColor:[UIColor yellowColor]];//view1 设置为黄色
    [self.view addSubview:view1];

    //根据view1的大小变换后创建view2;
    CGRect view2Rect = CGRectInset(view1.frame, 20, 20);//CGRectOffset替换
    UIView *view2 = [[UIView alloc] initWithFrame:view2Rect];
    [view2 setBackgroundColor:[UIColor redColor]];//view2 设置为红色
    [self.view addSubview:view2];
}

总结:

用途可以是UIButton改变可点击区域的大小。方法如下:

#import "TestButton.h"

@implementation TestButton

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    if (!self.userInteractionEnabled || self.isHidden || self.alpha <= 0.01) {
        return nil;
    }
    CGRect touchRect = CGRectInset(self.bounds, -20, -20);
    //如果点击的点point在touchRect这个范围内
    if (CGRectContainsPoint(touchRect, point)) {
        for (UIView *subview in [self.subviews reverseObjectEnumerator]) {
            CGPoint convertedPoint = [subview convertPoint:point fromView:self];
            UIView *hitTestView = [subview hitTest:convertedPoint withEvent:event];
            if (hitTestView) {//如果还有子类,则传递下去
                return hitTestView;
            }
        }
        //如果没有subView了,即此View为最上层View,则返回自己
        return self;
    }
    return nil;
}
上一篇下一篇

猜你喜欢

热点阅读