如何解决每次旋转时,UIView都会放错位置
我在下面有一个标尺(红色)和一个UIView(橙色):
https://developers.google.com/gmail/api/guides/push
当我旋转标尺时,UIView也旋转,但是它的位置不是我期望的:
我使用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,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
进行旋转
解决方法
您需要围绕notTouchedPoint
旋转视图。默认情况下,使用CGAffineTransform.init(rotationAngle:)
创建的旋转将围绕其中心旋转视图。
为此,请先将视图的中心平移到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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。