Drawing triangle/arrow on a line with CGContext

前端 未结 4 1217
南笙
南笙 2021-02-01 09:06

I am using the framework of route-me for working with locations. In this code the path between two markers(points) will be drawn as a line.

My Question: \"What code shou

4条回答
  •  隐瞒了意图╮
    2021-02-01 09:57

    - (void) drawLine: (CGContextRef) context from: (CGPoint) from to: (CGPoint) to 
    {
        double slopy, cosy, siny;
        // Arrow size
        double length = 10.0;  
        double width = 5.0;
    
        slopy = atan2((from.y - to.y), (from.x - to.x));
        cosy = cos(slopy);
        siny = sin(slopy);
    
        //draw a line between the 2 endpoint
        CGContextMoveToPoint(context, from.x - length * cosy, from.y - length * siny );
        CGContextAddLineToPoint(context, to.x + length * cosy, to.y + length * siny);
        //paints a line along the current path
        CGContextStrokePath(context);
    
        //here is the tough part - actually drawing the arrows
        //a total of 6 lines drawn to make the arrow shape
        CGContextMoveToPoint(context, from.x, from.y);
        CGContextAddLineToPoint(context,
                            from.x + ( - length * cosy - ( width / 2.0 * siny )),
                            from.y + ( - length * siny + ( width / 2.0 * cosy )));
        CGContextAddLineToPoint(context,
                            from.x + (- length * cosy + ( width / 2.0 * siny )),
                            from.y - (width / 2.0 * cosy + length * siny ) );
        CGContextClosePath(context);
        CGContextStrokePath(context);
    
        /*/-------------similarly the the other end-------------/*/
        CGContextMoveToPoint(context, to.x, to.y);
        CGContextAddLineToPoint(context,
                            to.x +  (length * cosy - ( width / 2.0 * siny )),
                            to.y +  (length * siny + ( width / 2.0 * cosy )) );
        CGContextAddLineToPoint(context,
                            to.x +  (length * cosy + width / 2.0 * siny),
                            to.y -  (width / 2.0 * cosy - length * siny) );
        CGContextClosePath(context);
        CGContextStrokePath(context);
    }
    

提交回复
热议问题