【问题标题】:How to Draw line at only 45 degree angle using CAShapeLayer in iPhone如何在 iPhone 中使用 CAShapeLayer 仅以 45 度角画线
【发布时间】:2013-07-29 06:19:17
【问题描述】:

我可以使用 CAShapeLayer 画线,但我试图仅以 45 度角画线。 线必须以 45 度角绘制,否则它将从视图中移除,如何使用 CAShapeLayer 绘制线,请帮助。 这是我的画线代码:

- (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;
}

【问题讨论】:

  • 您似乎已经弄清楚了程序。剩下的只是基本的数学。有机会重复三角函数(正弦、余弦、正切)。

标签: iphone ios objective-c uikit cashapelayer


【解决方案1】:

据我了解,您只需要检查 locationorigin 之间的角度是否为 45 度 +/- epsilon。所以你的代码可能看起来像这样:

// 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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多