从公共中心旋转一组 UIViews [英] Rotate group of UIViews together from common center
问题描述
这是对这个问题的跟进.我有一个类似的设置,有 n 个视图,我想将它们与旋转手势一起旋转.
This is a follow up to this question. I have a similar setup with n number of views, and I want to rotate them together with the rotation gesture.
我知道如何将旋转应用于单个视图,但在这里我想从公共中心而不是它们自己的中心旋转所有视图.
I know how to apply a rotation to a single view, but here I want to rotate all of them from common center instead of their own.
所以我尝试了这个方法
- 计算所有选定视图的公共中心点
- 设置指向这个公共中心的视图转换
- 并旋转视图
这就是我得到的
CGPoint newCenter =CGPointZero;
for(UIView *node in self.selectedNodes){
newCenter = CGPointMake(newCenter.x + node.center.x, newCenter.y + node.center.y);
}
newCenter = CGPointMake(newCenter.x/self.selectedNodes.count, newCenter.y/self.selectedNodes.count);
for(UIview *node in self.selectedNodes){
CGAffineTransform newTransform = CGAffineTransformMakeTranslation(groupCenter.x,groupCenter.y);
newTransform = CGAffineTransformRotate( node.transform,recognizer.rotation);
newTransform = CGAffineTransformTranslate(newTransform,-groupCenter.x, -groupCenter.y);
node.transform = newTransform;
}
但这并没有按预期工作.非常感谢任何帮助..
But this isn't working as expected. any help is much appreciated..
推荐答案
又是我.这是我进行轮换的方式:
it's me again. Here's how I did rotation:
let rotation = recognizer.rotation
recognizer.rotation = 0
let center = views.map { $0.center }.reduce(CGPoint.zero, +) / CGFloat(views.count)
views.forEach {
$0.transform = $0.transform.rotated(by: rotation)
let distance = $0.center - center
$0.center = center + CGPoint(
x: distance.x * cos(rotation) - distance.y * sin(rotation),
y: distance.y * cos(rotation) + distance.x * sin(rotation)
)
}
它与比例非常相似,你得到所有视图的中心,对于每个视图你得到到该中心的距离,使用公式旋转它以旋转一个点,并将旋转距离添加到所有视图的中心.
It's very similar to the scale, you get the center of all views, for each view you get the distance to that center, rotate it using the formula to rotate a point, and add that rotated distance to the center of all views.
这篇关于从公共中心旋转一组 UIViews的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!