开发者

can't get CALayer containsPoint to work

I've got an array of CALayers containing images which can be moved around by the user, and i'm trying to use containsPoint to detect if they have been touched - the code is as follows:

int num_objects = [pageImages count];

lastTouch = [touch locationInView:self];

CGRect objRect;
CALayer *objLayer;

for (int i = 0; i < num_objects; i++) {

    objLayer = [pageImages objectAtIndex:i];
    objRect = objLayer.bounds;

    NSLog(@"layerPos:%@, layerBounds:%@", NSStri开发者_如何学运维ngFromCGPoint(objLayer.position), NSStringFromCGRect(objRect));
    NSLog(@"point:%@", NSStringFromCGPoint(lastTouch));

    if ([objLayer containsPoint:lastTouch] == TRUE) {
        NSLog(@"touched object %d", i);
        return i;
    }
}

The information i'm outputting puts the touch within the bounds of the layer (i've assumed position is the centre of the layer, i haven't altered the anchor point. The layer hasn't been rotated or anything like that either), but containsPoint: doesn't return true. Can anyone see what i'm doing wrong, or suggest a different/better way to achieve what i want?


So .. found the problem - the point needs to be converted from superlayer coordinates in order to work with the layer containsPoint:

replace

if ([objLayer containsPoint:lastTouch] == TRUE) {

with

if ([objLayer containsPoint:[objLayer convertPoint:lastTouch fromLayer:objLayer.superlayer]] == TRUE) {

You can mess about with the co-ordinates yourself and use CGRectContainsPoint: (see comments above), but this is a simpler solution so i get to answer my own question for the first time. big tick for me, yay!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜