Reputation: 65877
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.
So I tried this approach
So this is what I got
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..
Upvotes: 1
Views: 62
Reputation: 19912
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.
Upvotes: 1