在我的应用中,根据用户拖动绘制一个圆圈。例如用户点击,即将要绘制的圆的中心,当他们拖动手指时,圆圈将增长到该点。这是有效的,除了某些原因,随着圆的半径增大,中心向下移动到右边。为什么会这样?这是我正在尝试的:
@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);
}
应该发生的事情是,中心点永远不会移动,圆圈应该增长。有什么想法吗?
答案 0 :(得分:1)
因为在CGRectMake
中你必须指定矩形的原点(和大小),而不是中心。
答案 1 :(得分:1)
CGRect rectangle = CGRectMake(center.x,center.y,distance, distance);
应该是:
CGRect rectangle = CGRectMake(center.x - distance, center.y - distance, distance * 2, distance * 2);
答案 2 :(得分:0)
CGRect rectangle = CGRectMake(center.x - distance, center.y - distance, distance * 2, distance * 2);