Drawing triangle/arrow on a line with CGContext

前端 未结 4 1235
南笙
南笙 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:53

    And here is Swift 4+ version for Friedhelm Brügge answer: (I'll draw it on image)

    func drawArrow(image: UIImage, ptSrc: CGPoint, ptDest: CGPoint) {
    
            // create context with image size
            UIGraphicsBeginImageContext(image.size)
            let context = UIGraphicsGetCurrentContext()
    
            // draw current image to the context
            image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
    
            var slopY: CGFloat, cosY: CGFloat, sinY: CGFloat;
            // Arrow size
            let length: CGFloat = 35.0;
            let width: CGFloat = 35.0;
    
            slopY = atan2((ptSrc.y - ptDest.y), (ptSrc.x - ptDest.x));
            cosY = cos(slopY);
            sinY = sin(slopY);
    
            //here is the tough part - actually drawing the arrows
            //a total of 6 lines drawn to make the arrow shape
            context?.setFillColor(UIColor.white.cgColor)
            context?.move(to: CGPoint(x: ptSrc.x, y: ptSrc.y))
            context?.addLine(to: CGPoint(x: ptSrc.x + ( -length * cosY - ( width / 2.0 * sinY )), y: ptSrc.y + ( -length * sinY + ( width / 2.0 * cosY ))))
            context?.addLine(to: CGPoint(x: ptSrc.x + (-length * cosY + ( width / 2.0 * sinY )), y: ptSrc.y - (width / 2.0 * cosY + length * sinY )))
            context?.closePath()
            context?.fillPath()
    
            context?.move(to: CGPoint(x: ptSrc.x, y: ptSrc.y))
            context?.addLine(to: CGPoint(x: ptDest.x +  (length * cosY - ( width / 2.0 * sinY )), y: ptDest.y +  (length * sinY + ( width / 2.0 * cosY ))))
            context?.addLine(to: CGPoint(x: ptDest.x +  (length * cosY + width / 2.0 * sinY), y: ptDest.y -  (width / 2.0 * cosY - length * sinY)))
            context?.closePath()
            context?.fillPath()
    
            // draw current context to image view
            imgView.image = UIGraphicsGetImageFromCurrentImageContext()
    
            //close context
            UIGraphicsEndImageContext()
        }
    

提交回复
热议问题