0

I've created a custom UIView where I'll eventually have 10 zones a user can tap. When a zone is tapped, I want to overlay a low-alpha layer to indicate their selection.

Unfortunately, when I tap a section, the CALayer I've created is drawing outside the bounds of my custom view. It seems as though both my x and y coordinates are off.

Here is the drawRect method inside my custom view:

- (void)drawRect:(CGRect)dirtyRect
{
    if (touchPoint.x > 0 || touchPoint.y > 0){
        CGRect bounds = [self bounds];

        float widthOfArea = bounds.size.width / 10.0;

        float sectionNumber = round(touchPoint.x / widthOfArea);

        touchOverlayLayer = [[CALayer alloc] init];

        [touchOverlayLayer setBounds:CGRectMake(0.0, 0.0, widthOfArea, bounds.size.height)];

        [touchOverlayLayer setPosition:CGPointMake(widthOfArea * sectionNumber, self.bounds.origin.y)];

        UIColor *greyish = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:.5];

        CGColorRef cggreyish = [greyish CGColor];

        [touchOverlayLayer setBackgroundColor:cggreyish];

        [[self layer] addSublayer:touchOverlayLayer];
    }
}

And the resulting display is attached.Layers not drawing in the correct place

4

2 回答 2

4

setPosition puts the anchor point of your layer at the position. The default anchor point of a layer is the centre. This ties up pretty well with what you're seeing.

You can set the anchor point to 0,0 then set the position, and you should be fine.

Here's a brief explanation of anchor points and so on.

It is a bit tricky. The frame, bounds and position are all tied together. In your situation, you could just set the frame of the layer and you'd be fine, the anchor point is more typically used for when you are going to rotate or otherwise transform the layer - it becomes the origin of the transformation. If you change the anchor point it moves the layer, but then you're setting the position so it moves it back again. The docs are a bit weak on this but there are plenty of examples on the web.

The anchor point becomes the location that everything happens around. So if you set the position, the layer moves so that it's anchor point is at that position. If you rotate the layer, it rotates around the anchor point, etc.

于 2012-06-01T05:49:28.680 回答
0

Just add only this line

touchOverlayLayer.anchorPoint=CGPointMake(0, 0);

default anchorPoint is 0.5,0.5 means on the centre of the layer.

于 2012-06-01T06:01:58.527 回答