我可以使用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;
}
答案 0 :(得分:0)
根据我的理解,您只需要检查location
和origin
之间的角度是否为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;
}
}