2016-12-14 16 views
2

私は迅速に新しいです、私はmapViewと呼ばれる画像上に2点の間に線を描きたい、私はCGContextを使用しようとしましたが、何の助けにもなりません。ありがとう。イメージ上の2点間を迅速に3線で描画する方法は?

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() 
+0

@Dev_Tandelが言ったようにあなたは、ポリライン –

+0

を探しているかもしれないあなたはGoogleマップを使用していて、ポリラインを描きたいか、単にあなたは上の2点間に線を描きたいです任意のUIImage。 –

答えて

3

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) 
+0

ご協力いただきありがとうございます。私は他の質問をしてください:どのように画像からこれらの行を削除することができますか? removeFromSuperViewを試してみましたが、画像上で他のビューを持っていましたが、削除する必要はありません。 –

+0

'lineView.removeFromSuperview()'を使うことができます。他のオプションは、LineViewの描画機能を制御するだけです。あなたは欲しい。 –

+0

ありがとう、私はポイントを送信することによって動的にしようとしましたが、私はできない、動的にする方法を教えてください? –

関連する問題