Swift绘制无限正弦曲线(UIBezierpath)

时间:2016-07-12 15:01:49

标签: swift user-interface graph

class GraphView: UIView {

private let axesDrawer = AxesDrawer()
private var scale: CGFloat = 1.0 { didSet { setNeedsDisplay() } }
private var axesCenter: CGPoint? { didSet { setNeedsDisplay() } }
private var positionX: CGFloat = 0 { didSet { setNeedsDisplay() } }

func changeScale(recognizer: UIPinchGestureRecognizer) {
    switch recognizer.state {
    case .Changed, .Ended:
        scale *= recognizer.scale
        recognizer.scale = 1.0
    default: break
    }
}

func moveAxes(recognizer: UIPanGestureRecognizer) {
    switch recognizer.state {
    case .Changed:
        if axesCenter == nil {
            axesCenter = CGPoint(x: self.frame.midX, y: self.frame.midY)
        }
        let changePoint = recognizer.translationInView(self)
        axesCenter = CGPoint(x: axesCenter!.x + changePoint.x, y: axesCenter!.y + changePoint.y)
        positionX += changePoint.x
        recognizer.setTranslation(CGPoint(x: 0.0, y: 0.0), inView: self)
    default:
        break
    }
}

func drawGraph() -> UIBezierPath {
    let path = UIBezierPath()
    let positionY = (axesCenter == nil) ? frame.height / 2 : (axesCenter?.y)! // find the vertical center

    path.moveToPoint(CGPoint(x: self.frame.minX, y: positionY))

    for i in Int(frame.minX)...Int(frame.maxX) {
        let x = CGFloat(i) + positionX
        let y = (sin(Double(i) * 0.1) * Double(axesDrawer.minimumPointsPerHashmark) * Double(scale)) + Double(positionY)
        path.addLineToPoint(CGPoint(x: x, y: CGFloat(y)))
    }

    path.lineWidth = 1
    return path
}

override func drawRect(rect: CGRect) {
    axesDrawer.contentScaleFactor = self.contentScaleFactor
    axesDrawer.drawAxesInRect(self.bounds, origin: axesCenter ?? CGPoint(x: self.frame.midX, y: self.frame.midY), pointsPerUnit: CGFloat(50) * scale)
    UIColor.redColor().set()
    drawGraph().stroke()
}
}

走向:

left side

right side

我试图绘制"无限"正弦曲线。问题是,当我试图移动视图时,它不会重绘自己。

如果您查看我提供的链接,left侧会显示无限行,如果您转到right,曲线就会停止。

每次尝试移动视图时,如何更新要重绘的曲线的UI?

0 个答案:

没有答案