限制平移手势移动到90度

如果我为前者创build了一行 在图中显示为通过CAShapeLayer连接A和B,在该行的中心我有一个UIView ,其中包含了平移手势。

如何使UIView移动到某个方向创build90度,如图所示,红线表示UIView可以移动的方向?

中点应该从线的中心开始,沿着我已经更新的图中所示的方向。

在这里输入图像说明

我假设你可以处理锅,你可以得到接触点。 你想要的是计算触摸点到红线的投影,并将UIView放置在那里。

红线垂直于AB,构成AB的中点。

 // //when the pan gesture recognizer reports state change event /*you have CGPoint A; CGPoint B; CGPoint T; //touch point */ //midpoint CGPoint M = {(A.x+Bx)/2, (A.y+By)/2}; //AB distance CGFloat distAB = sqrtf(powf(Bx-Ax, 2) + powf(By-Ay, 2)); //direction of the red line with unit length CGVector v = {(By-Ay)/distAB, -(Bx-Ax)/distAB}; // vector from midpoint to touch point CGVector MT = {Tx-Mx, Ty-My}; // dot product of v and MT // which is the signed distance of the projected point from M CGFloat c = v.dx*MT.dx + v.dy*MT.dy; // projected point is M + c*v CGPoint projectedPoint = {Mx + c*v.dx, My + c*v.dy}; //TODO: set the center of the moving UIView to projectedPoint 

更新:

你的评论揭示,这种营养的利用对你来说还不够清楚。 所以我把这个想法embedded了一个工作的例子。

 @interface ViewController () @end @implementation ViewController { CGPoint A; CGPoint B; CGPoint M; //midpoint of AB CGVector v; //direction of the red line with unit length UIView* pointMover; } - (void)viewDidLoad { [super viewDidLoad]; A = CGPointMake(50,50); B = CGPointMake(300,200); M = CGPointMake((A.x+Bx)/2, (A.y+By)/2); CGFloat distAB = sqrtf(powf(Bx-Ax, 2) + powf(By-Ay, 2)); v = CGVectorMake((By-Ay)/distAB, -(Bx-Ax)/distAB); pointMover = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)]; pointMover.center = M; pointMover.backgroundColor = [UIColor blueColor]; pointMover.layer.cornerRadius = 22.0f; [self.view addSubview:pointMover]; UIPanGestureRecognizer* panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)]; [pointMover addGestureRecognizer:panRecognizer]; UIBezierPath* blackLinePath = [UIBezierPath bezierPath]; [blackLinePath moveToPoint:A]; [blackLinePath addLineToPoint:B]; CAShapeLayer *blackLineLayer = [CAShapeLayer layer]; blackLineLayer.path = [blackLinePath CGPath]; blackLineLayer.strokeColor = [[UIColor blackColor] CGColor]; blackLineLayer.lineWidth = 2.0; [self.view.layer addSublayer:blackLineLayer]; } - (void)handlePan:(UIPanGestureRecognizer*)recognizer { //touch point CGPoint T = [recognizer locationInView:self.view]; // vector from midpoint to touch point CGVector MT = {Tx-Mx, Ty-My}; // dot product of v and MT CGFloat c = v.dx*MT.dx + v.dy*MT.dy; // projected point is M + c*v CGPoint projectedPoint = {Mx + c*v.dx, My + c*v.dy}; pointMover.center = projectedPoint; } @end