2016-05-19 43 views
-2

如果我已經爲前例創建了一行。如圖所示連接A和B通過CAShapeLayer,並在該線的中心我有一個UIView其中集成了平移手勢。限制平移手勢移動到90度

如何使UIView移動到與該線成90度的某個方向,如圖所示,紅色線表示UIView可以移動的方向?

中點應該從該線的中心開始移動,沿着我已更新的圖中所示的方向。

enter image description here

回答

3

我相信你能處理的鍋,你能得到觸摸點。你想要的是計算觸摸點到紅線的投影並將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+B.x)/2, (A.y+B.y)/2}; 

//AB distance 
CGFloat distAB = sqrtf(powf(B.x-A.x, 2) + powf(B.y-A.y, 2)); 

//direction of the red line with unit length 
CGVector v = {(B.y-A.y)/distAB, -(B.x-A.x)/distAB}; 

// vector from midpoint to touch point 
CGVector MT = {T.x-M.x, T.y-M.y}; 

// 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 = {M.x + c*v.dx, M.y + c*v.dy}; 

//TODO: set the center of the moving UIView to projectedPoint 

UPDATE:

您的評論顯示,這soulution的利用率是不是你不夠清楚。因此,我將這個想法嵌入了一個工作示例。

@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+B.x)/2, (A.y+B.y)/2); 
    CGFloat distAB = sqrtf(powf(B.x-A.x, 2) + powf(B.y-A.y, 2)); 
    v = CGVectorMake((B.y-A.y)/distAB, -(B.x-A.x)/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 = {T.x-M.x, T.y-M.y}; 

    // dot product of v and MT 
    CGFloat c = v.dx*MT.dx + v.dy*MT.dy; 

    // projected point is M + c*v 
    CGPoint projectedPoint = {M.x + c*v.dx, M.y + c*v.dy}; 

    pointMover.center = projectedPoint; 
} 


@end 
+0

可能是你誤會了我的疑慮,重點應該從行的中間開始移動,你可以在更新後的問題中看到。 –

+0

也是當用戶將中點放在某個點並重新開始重新定位時,那麼從那裏開始而不是從中點的中心開始。 –