首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在iPhone中用CAShapeLayer绘制45度角直线

如何在iPhone中用CAShapeLayer绘制45度角直线
EN

Stack Overflow用户
提问于 2013-07-29 14:19:17
回答 1查看 884关注 0票数 1

我可以使用CAShapeLayer绘制直线,但我尝试仅以45度角绘制一条直线。直线必须以45度角绘制,否则它将从视图中删除,我如何使用CAShapeLayer绘制直线,请帮助。下面是我绘制线条的代码:

代码语言:javascript
复制
- (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;
}
EN

回答 1

Stack Overflow用户

发布于 2013-08-27 05:13:13

据我所知,你只需要检查locationorigin之间的角度是否为45度正负。因此,您的代码可能如下所示:

代码语言:javascript
复制
// 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;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17917185

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档