سؤال

In my app, a circle is drawn based on a users drag. e.g. a user taps, that is the center of a circle that will be drawn, and as they drag their finger, the circle will grow to that point. This works, except for some reason the center moves down and to the right as the radius of the circle grows. Why is this happening? Here is what I am trying:

@implementation CircleView{
    CGPoint center;
    CGPoint endPoint;
    CGFloat distance;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    center = [touch locationInView:self];
    [self setNeedsDisplay];
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    endPoint = [touch locationInView:self];
    CGFloat xDist = (endPoint.x - center.x);
    CGFloat yDist = (endPoint.y - center.y);
    distance = sqrt((xDist * xDist) + (yDist * yDist));
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2.0);
    CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
    CGRect rectangle = CGRectMake(center.x,center.y,distance, distance);
    CGContextAddEllipseInRect(context, rectangle);
    CGContextStrokePath(context);
}

What should be happening is that center point never ever moves, and the circle should just grow. Any ideas?

هل كانت مفيدة؟

المحلول

CGRect rectangle = CGRectMake(center.x,center.y,distance, distance);

should be:

CGRect rectangle = CGRectMake(center.x - distance, center.y - distance, distance * 2, distance * 2);

نصائح أخرى

Because in CGRectMake you have to specify the origin (and the size) of the rectangle, not the center.

CGRect rectangle = CGRectMake(center.x - distance, center.y - distance, distance * 2, distance * 2);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top