gpt4 book ai didi

ios - 如何将 View /图层的移动路径限制为贝塞尔曲线路径?

转载 作者:搜寻专家 更新时间:2023-11-01 07:17:05 30 4
gpt4 key购买 nike

在问这个问题之前,我搜索了SO:

iPhone-Move UI Image view along a Bezier curve path

但并没有给出明确的答复。

我的要求是这样的,我有一个贝塞尔曲线路径和一个 View (或层,如果可以的话),我想添加 pan gesture 到 View ,和 View (或层)' s 移动路径必须约束为贝塞尔曲线路径。

enter image description here

我的代码如下:

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 移动 View /图层时, View 将在贝塞尔曲线路径上移动。

最佳答案

如果贝塞尔曲线路径偏离直线,那么你可以找到直线的斜率,对于 x 或 y 的每一次变化,你都可以计算贝塞尔曲线路径的位置var y :Float = (slope * (xPos-previousCoord.x))+previousCoord.y; xPos 不断变化。同样,你可以找到 x。对于任何带有线段的闭合形状,您都可以使用它。

但是如果你需要它作为圆,那么你需要将笛卡尔坐标转换为极坐标坐标。即..,从坐标你可以找到角度,然后从那个角度,你有半径所以通过使用那个角度你需要从中找到笛卡尔坐标。 enter image description here

θ = tan-1 ( 5/12 )

您主要需要使用三个坐标,一个是圆心,第二个是您的触摸点,最后一个是 (touchpoint.x, centreofcircle.y)。从圆心计算两个坐标之间的距离你有 θ 和圆的半径然后使用找到点

x = r × cos( θ )

y = r × sin( θ )

不要把图中的r误认为是圆的半径,图中的r是三个坐标的斜边。您应该计算接触点中 x 的每个变化。

希望它有效。但对于不规则形状,我不确定如何找到。

关于ios - 如何将 View /图层的移动路径限制为贝塞尔曲线路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41560182/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com