首页 > 解决方案 > 用触摸画线

问题描述

我是 swift 新手,没有处理核心图形的经验。我需要在 ios swift 中开发一个应用程序来绘制图形。这里的图是指图论。我需要通过点击屏幕来绘制节点,并在两个节点被选中时在它们之间画线。到目前为止,我只能画圆圈,但我需要在触摸两点时在两者之间出现一条线。如果我已经画了一个圆圈,我需要它,当他们再次点击时,他们可以移动。我怎样才能画线?

我将感谢任何支持

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

         self.view.backgroundColor = UIColor.lightGray
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            // Set the Center of the Circle
            // 1
            let circleCenter = touch.location(in: view)

            // Set a random Circle Radius
            // 2
            let circleWidth = CGFloat(25.7) //+ (arc4random() % 50))
            let circleHeight = circleWidth

            // Create a new CircleView
            // 3
            let circleView = CircleView(frame: CGRect(x: circleCenter.x, y: circleCenter.y, width: circleWidth, height: circleHeight))
            view.addSubview(circleView)
        }
    }
}

类 CircleView.swift

class CircleView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.clear
    }

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

    override func draw(_ rect: CGRect) {
        // Get the Graphics Context
        if let context = UIGraphicsGetCurrentContext() {

            // Set the circle outerline-width
            context.setLineWidth(5.0);

            // Set the circle outerline-colour
            UIColor.red.set()

            // Create Circle
            let center = CGPoint(x: frame.size.width/2, y: frame.size.height/2)
            let radius = (frame.size.width - 10)/2
            context.addArc(center: center, radius: radius, startAngle: 0.0, endAngle: .pi * 2.0, clockwise: true)

            // Draw
            context.strokePath()
        }
    }
}

标签: iosswift

解决方案


推荐阅读