之前問這個問題,我已經搜查了SO:如何限制視圖/圖層的移動路徑到貝塞爾曲線路徑?
iPhone-Move UI Image view along a Bezier curve path
但它沒有給出明確的答案。我的要求是這樣的,我有一個貝塞爾路徑和一個視圖(或層,如果確定),我想添加pan gesture
到視圖,並且視圖(或圖層)的移動路徑必須約束到貝塞爾路徑。
我的代碼如下:
的MainDrawView.swift
:
import UIKit
class MainDrawView: UIView {
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
drawArc()
}
func drawArc() {
let context = UIGraphicsGetCurrentContext()
// set start point
context?.move(to: CGPoint.init(x: 0, y: 400))
//draw curve
context?.addQuadCurve(to: CGPoint.init(x: 500, y: 250), control: CGPoint.init(x: UIScreen.main.bounds.size.width, y: 200))
context?.strokePath()
}
}
的ViewController.swift
:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var clickButton: UIButton!
lazy var view1:UIView = {
let view: UIView = UIView.init(frame: CGRect.init(origin: CGPoint.init(x: 0, y: 0), size: CGSize.init(width: 10, height: 10)))
view.center = CGPoint.init(x: UIScreen.main.bounds.size.width/2.0, y: UIScreen.main.bounds.size.height/2.0)
view.backgroundColor = UIColor.red
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
initData()
initUI()
}
func initData() {
}
func initUI() {
self.clickButton.isHidden = true
// init the view
self.view.addSubview(self.view1)
}
}
編輯-1
我深需求量的是,當我使用pan guester
移動視圖/層,視圖將貝塞爾路徑上移動。
它可以是CALayers嗎?至少在我看來,更容易完成UIViews。一個UIView可以有幾個CALayers。如果這對你有用,我有代碼可以做到這一點。 – dfd
@dfd,好的,使用CALayer也可以實現它。 – aircraft
@aircraft - 那麼我是否正確理解你,你是否想讓用戶激活一個'UIPanGestureRecognizer',並且隨着更新,廣場將沿着路徑移動? – Pierce