【问题标题】:How to draw a line between two points over an image in swift 3?如何在swift 3中的图像上的两点之间画一条线?
【发布时间】:2016-12-14 10:04:27
【问题描述】:

我是 swift 新手,我想在我称为 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()

【问题讨论】:

  • 您可能正在寻找折线
  • 就像@Dev_Tandel 说的那样,您是在使用谷歌地图并想要绘制折线还是只想在任何 UIImage 上的两点之间绘制一条线。

标签: swift cgcontext cgcontextdrawimage


【解决方案1】:

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

游乐场实现示例:

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 但我对图像有其他视图,我不想删除它,谢谢
  • 你可以使用lineView.removeFromSuperview(),另外一种选择是控制LineView中的draw函数只显示你想要的。
  • 非常感谢,我尝试通过发送积分使其动态化但我不能,请问如何使其动态化?
  • 抱歉,这是一个更大的话题,对于 Stack Overflow 格式来说太大了。我建议阅读 iOS 教程。
猜你喜欢
  • 2013-10-03
  • 2020-02-16
  • 1970-01-01
  • 2016-08-25
  • 2014-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多