gpt4 book ai didi

swift - 每次旋转时 UIView 都会放错位置

转载 作者:行者123 更新时间:2023-12-04 08:45:33 24 4
gpt4 key购买 nike

我在它下面有一个标尺(红色)和一个 UIView(橙色),如下所示:
enter image description here
当我旋转标尺时,UIView 也会旋转,但它的位置不是我所期望的:
enter image description here
我用 UILongPressGestureRecognizer旋转尺子,当我握住手指并移动时,我得到一个angle重新绘制标尺,它工作得很好,但不适用于 UIView。
我如何创建和旋转 UIView:

 func createUIViewOutSideRuler(touchedPoint:CGPoint, notTouchedPoint:CGPoint, angle: CGFloat) -> UIView{
let viewWidth = distanceFromTwoPoints(touchedPoint, notTouchedPoint)

let view = UIView(frame: CGRect(x:notTouchedPoint.x, y: notTouchedPoint.y , width: viewWidth, height: dotLineSize * 2))

view.transform = CGAffineTransform(rotationAngle: angle);

view.backgroundColor = .orange
self.addSubview(view)
return view
}
根据 Sweeper 评论更新
let view = UIView(frame: CGRect(x:notTouchedPoint.x, y: notTouchedPoint.y , width:  viewWidth, height: dotLineSize * 2))

let vectorToStartPoint = CGPoint(x: view.center.x - touchedPoint.x,
y: view.center.y - touchedPoint.y )
view.transform = CGAffineTransform(translationX: vectorToStartPoint.x, y: vectorToStartPoint.y)
.rotated(by: angle)
.translatedBy(x: -vectorToStartPoint.x, y: -vectorToStartPoint.y)
结果:
备注 : 我拖了 touchedPoint旋转
围绕 touchedPoint enter image description here
围绕 notTouchedPoint enter image description here

最佳答案

您需要围绕 notTouchedPoint 旋转 View .默认情况下,使用 CGAffineTransform.init(rotationAngle:) 创建的旋转将围绕其中心旋转 View 。
为此,首先将 View 的中心转换为 startPoint ,旋转它,然后将其平移回来。

let vectorToNotTouchedPoint = CGPoint(x: view.center.x - notTouchedPoint.x
y: view.center.y - notTouchedPoint.y)
view.transform = CGAffineTransform(translationX: vectorToNotTouchedPoint.x, y: vectorToNotTouchedPoint.y)
.rotated(by: angle)
.translatedBy(x: -vectorToNotTouchedPoint.x, y: -vectorToNotTouchedPoint.y)

关于swift - 每次旋转时 UIView 都会放错位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64346193/

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