【问题标题】:How to rotate a UIView around it's proper center without distortion / skew如何围绕正确的中心旋转 UIView 而不会扭曲/歪斜
【发布时间】:2018-01-28 19:04:26
【问题描述】:

我已经构建了自己的动画引擎,我想在渲染的每一帧上设置 UI 视图的旋转 (60fps)

我现在制作了一个视频来展示当前的问题。

它相当接近,但它仍在以一种奇怪的方式旋转:

https://www.youtube.com/watch?v=1ZKK4r0-6i4

我已经实现了一个自定义的 CustomUIView 类,它继承自 UI 视图。这具有平移、缩放和旋转属性,所以当我变换矩阵时,所有 3 个都发生在同一个动作中。

var t = CGAffineTransform( translationX: self.translation.x, y: 
self.translation.y );
// Apply scaling
t = t.scaledBy( x: self.scaling.x, y: self.scaling.y );
// Apply rotation
t = t.rotated(by:self.rotation)
self.transform = t

大小和宽度设置如下:

view.frame.size.width = parseSize(value, axis: "width")
view.layer.bounds.size.width = parseSize(value, axis: "width")    

我正在尝试设置这两个属性,但我不确定这是否正确。

我已经设置了很多锚点,也尝试了视图的整体中心点。

【问题讨论】:

标签: ios swift uiview graphics uikit


【解决方案1】:

问题是我在每个动画帧中设置了不止一次的变换。这导致了具有不同值的复合效应。您需要组织变量,以便在属性修改期间只设置一次转换。

【讨论】:

  • @Krunal 啊,抱歉 :( 但您的回答并没有帮助我找到解决方案。我的代码库中发生了很多事情,这更像是我的代码流的架构问题,比任何人都可以提供的帮助(最终变得非常简单)
  • 问题是我把整个过程做了两次,真的没有任何工作代码可以显示吗?
【解决方案2】:

这应该可以帮助您根据您的要求使其工作:

@IBOutlet var scaleRotateImage: UIImageView!
func scaleNTransform() -> Void {

    scaleRotateImage.layer.cornerRadius = scaleRotateImage.frame.size.height/2.0
    scaleRotateImage.clipsToBounds = true

    let scaleTransform = CGAffineTransform(scaleX: 3.0, y: 3.0)  // Scale
    let rotateTransform = CGAffineTransform(rotationAngle: CGFloat.pi) // Rotation
    let hybridTransform = scaleTransform.concatenating(rotateTransform) // Both Scale + Rotation

    // Outer block of animation
    UIView.animate(withDuration: 5.0, animations: {
        self.scaleRotateImage.transform = scaleTransform
        self.view.layoutIfNeeded()
    }) { (isCompleted) in

        // Nested block of animation
        UIView.animate(withDuration: 5.0, animations: {
            self.scaleRotateImage.transform = hybridTransform
            self.view.layoutIfNeeded()
        })

    }


}


结果

【讨论】:

  • 我不想使用内置动画系统。另外,我想平移和旋转(我也可以包括比例,但这不是必需的)
【解决方案3】:

而不是使用

var t = CGAffineTransform( translationX: self.translation.x, y: 
self.translation.y );

使用

var t = CGAffineTransform(rotationAngle: CGFloat(Double.pi*self.rotation/180.0))

这将在不改变其位置的情况下从中心旋转您的视图。

【讨论】:

  • 问题是,我想同时改变位置和旋转。这改变了这个旋转,但现在它在父视图的左上角做了一个巨大的循环。
  • 我知道改变旋转或翻译的顺序会产生不同的结果,但都不能让我得到我想要的。如果我只是旋转,它会完美运行。但是,如果我翻译它,它会按照描述移动。如果我通过改变它的框架原点或中心来移动 UIView,它似乎移动得非常糟糕(倾斜等)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-30
  • 2010-10-05
  • 2014-01-24
  • 2013-09-17
  • 1970-01-01
  • 2014-02-17
  • 1970-01-01
相关资源
最近更新 更多