简体   繁体   English

如何通过CGRect过滤NSArray中的CGPoints

[英]How to filter CGPoints in an NSArray by CGRect

I have an NSArray with CGPoints . 我有一个带有CGPointsNSArray I'd like to filter this array by only including points within a rect. 我想通过在rect中包含点来过滤这个数组。

How can I formulate an NSPredicate such that each point satisfies this predicate: 我如何制定一个NSPredicate ,使每个点满足这个谓词:

CGRectContainsPoint(windowRect, point); CGRectContainsPoint(windowRect,point);

Here's the code so far: 这是迄今为止的代码:

NSArray *points = [NSArray arrayWithObjects: [NSValue valueWithCGPoint:pointAtYZero] ,
                                             [NSValue valueWithCGPoint:pointAtYHeight],
                                             [NSValue valueWithCGPoint:pointAtXZero],
                                             [NSValue valueWithCGPoint:pointAtXWidth],
                                             nil];


NSPredicate *inWindowPredicate = [NSPredicate predicateWithFormat:@"CGRectContainsPoint(windowRect, [point CGPointValue])"];
NSArray *filteredPoints = [points filteredArrayUsingPredicate:inWindowPredicate];

You cannot do this with the predicate format syntax, but you can use a block: 您不能使用谓词格式语法执行此操作,但可以使用块:

NSArray *points = ...;
CGRect windowRect = ...;    
NSPredicate *inWindowPredicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
    CGPoint point = [evaluatedObject CGPointValue];
    return CGRectContainsPoint(windowRect, point);
}];
NSArray *filteredPoints = [points filteredArrayUsingPredicate:inWindowPredicate];

Note that it's not possible to use block-based predicates for Core Data fetch requests. 请注意,无法对Core Data获取请求使用基于块的谓词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM