2013-07-29 93 views
0

我可以使用CAShapeLayer繪製線條,但我只想以45度角繪製線條。 線必須以45度角繪製,否則將從視圖中移除,我如何使用CAShapeLayer繪製線,請幫助。 這裏是我的繪製代碼行:如何使用iPhone中的CAShapeLayer以45度角繪製線條

- (void)handlePanGesture:(UIPanGestureRecognizer *)gesture 
{ 
static CGPoint origin; 
CGPoint location ; 
if (gesture.state == UIGestureRecognizerStateBegan) 
{ 
    shapeLayer = [self createShapeLayer:gesture.view]; 
    origin = [gesture locationInView:gesture.view]; 
    UIView *tappedView = [gesture.view hitTest:origin withEvent:nil]; 
    UILabel *tempLabel = (UILabel *)tappedView; 
    [valuesArray addObject:tempLabel]; 

    if(valuesArray) 
    { 
     [valuesArray removeAllObjects]; 
    } 
    valuesArray = [[NSMutableArray alloc] init]; 
} 
else if (gesture.state == UIGestureRecognizerStateChanged) 
{ 
     path1 = [UIBezierPath bezierPath]; 
     [path1 moveToPoint:origin]; 
     location = [gesture locationInView:gesture.view]; 
     [path1 addLineToPoint:location]; 
     shapeLayer.path = path1.CGPath; 
} 
} 

- (CAShapeLayer *)createShapeLayer:(UIView *)view 
{ 
shapeLayer = [[CAShapeLayer alloc] init]; 
shapeLayer.fillColor = [UIColor clearColor].CGColor; 
shapeLayer.strokeColor = [UIColor redColor].CGColor; 
shapeLayer.lineCap = kCALineCapRound; 
shapeLayer.lineJoin = kCALineJoinRound; 
shapeLayer.lineWidth = 10.0; 
[view.layer addSublayer:shapeLayer];//view.layer 

return shapeLayer; 
} 
+0

你似乎有編程想通了。其餘的只是基本的數學。有機會重複三角(正弦,餘弦,正切)。 –

回答

0

據我瞭解,你只需要檢查locationorigin之間的夾角爲45度+/-小量。所以你的代碼可能看起來像這樣:

// EPSILON represent the acceptable error in pixels 
#define EPISLON 2 

// ... 

else if (gesture.state == UIGestureRecognizerStateChanged) 
{ 
    path1 = [UIBezierPath bezierPath]; 
    [path1 moveToPoint:origin]; 

    location = [gesture locationInView:gesture.view]; 

    // only add the line if the absolute different is acceptable (means less than EPSILON) 
    CGFloat dx = (location.x - origin.x), dy = (location.y - origin.y); 
    if (fabs(fabs(dx) - fabs(dy)) <= EPISLON) { 
     [path1 addLineToPoint:location]; 
     shapeLayer.path = path1.CGPath; 
    } 
}