Rotate group of UIViews together from common center

孤人 提交于 2019-12-11 06:58:59

问题


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

  • Calculated a common center point of all selected views
  • Set the view translation pointing to this common center
  • And rotated the view

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..


回答1:


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.



来源:https://stackoverflow.com/questions/52052198/rotate-group-of-uiviews-together-from-common-center

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!