如何在Swift 3中在图像上绘制两个点之间的直线?

6

我是新手,想在我称为mapView的图像上在2个点之间绘制一条线。我尝试使用CGContext但没有结果,有什么建议可以帮助吗?谢谢。

UIGraphicsBeginImageContext(mapView.bounds.size)
    let context : CGContext = UIGraphicsGetCurrentContext()!
    context.addLines(between: [CGPoint(x:oldX,y:oldY), CGPoint(x:newX, y:newY)])
    context.setStrokeColorSpace(CGColorSpaceCreateDeviceRGB())
    context.setStrokeColor(UIColor.blue.cgColor.components!)
    context.setLineWidth(3)
    mapView?.image?.draw(at: CGPoint(x:0, y:0))
    context.strokePath()
    mapView.image = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

你可能正在寻找polyLine。 - Devang Tandel
就像@Dev_Tandel所说,您是否正在使用Google地图并想要绘制polyLine,还是只想在任何UIImage上绘制两个点之间的线条。 - Manish Pathak
1个回答

6

一种选择是向您的图像视图添加一个子视图,并将线条绘制代码添加到其 draw(_ rect: CGRect) 方法中。

示例 Playground 实现:

class LineView : UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.init(white: 0.0, alpha: 0.0)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func draw(_ rect: CGRect) {
        if let context = UIGraphicsGetCurrentContext() {
            context.setStrokeColor(UIColor.blue.cgColor)
            context.setLineWidth(3)
            context.beginPath()
            context.move(to: CGPoint(x: 5.0, y: 5.0)) // This would be oldX, oldY
            context.addLine(to: CGPoint(x: 50.0, y: 50.0)) // This would be newX, newY
            context.strokePath()
        }
    }
}


let imageView = UIImageView(image: #imageLiteral(resourceName: "image.png")) // This would be your mapView, here I am just using a random image
let lineView = LineView(frame: imageView.frame)
imageView.addSubview(lineView)

谢谢你的帮助,已经完成了。我还有一个问题:如何从图像中删除这些行?我尝试使用removeFromSuperView,但是我在图像上有其他视图,我不想删除它们,谢谢。 - mohammed HASSAN
你可以使用lineView.removeFromSuperview()方法,另一种选择是控制LineView的绘制函数只显示想要的内容。 - Jozef Legény
非常感谢,我尝试通过发送点数使其动态化,但是我无法做到,请问如何使其动态化? - mohammed HASSAN
抱歉,这是一个更大的话题,超出了 Stack Overflow 的范围。我建议阅读 iOS 教程。 - Jozef Legény

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接