【问题标题】:Animating the bounds property of a UIView为 UIView 的 bounds 属性设置动画
【发布时间】:2014-04-02 16:39:18
【问题描述】:

根据可用的 Apple 文档here,UIView 的bounds 属性可以设置动画。

为了以编程方式旋转我的一个视图(在本例中从纵向到横向),我实现了以下代码:

 float w = controlsView.bounds.size.width;
 float h = controlsView.bounds.size.height;

 CGAffineTransform T = CGAffineTransformMakeRotation(M_PI/2);

 UIViewContentMode oldContentMode = controlsView.contentMode;
 controlsView.contentMode = UIViewContentModeRedraw;

 [UIView animateWithDuration:1.0 animations:^{
        controlsView.bounds = CGRectMake(0, 0, h, w);
        controlsView.transform = T;
 }];

 controlsView.contentMode = oldContentMode;

我为 contentMode 添加了两条指令,因为我在 StackOverflow 上的某处读到 contentMode 必须设置为该值,以便 UIView 在修改 bounds 属性时重绘内容(但是,在在这种情况下,它不会以任何方式影响行为)。

该代码的问题在于 UIView 没有通过动画调整大小,而是一次性调整大小。

执行该代码,UIView 首先被调整大小(没有动画),然后用动画旋转。

如何为调整大小设置动画?

-- 更新--

我尝试结合缩放和旋转变换。 UIView 在动画中旋转和缩放,但最后它的bounds 属性没有改变:即使它已经旋转到横向(在我的 iPhone 上应该是 568x320),它的宽度和高度保持在纵向值 (320x568)。事实上,controlsView 上的 UI 控件已变形(纵横比错误)并出现拉伸。

【问题讨论】:

  • 为什么不使用缩放和旋转变换?

标签: ios uiview core-animation


【解决方案1】:

这对我有用 UIViewAnimationOptions.LayoutSubviews (Swift):

UIView.animateWithDuration(1.0,delay:0.0,
options:UIViewAnimationOptions.LayoutSubviews,
animations:{ () -> Void in
  myView.transform = myRotationTransform
  myView.bounds = myBounds
}, completion: nil)

(没有显式缩放也没有改变 contentMode)

【讨论】:

    【解决方案2】:

    问题在于,当您设置 transform 属性时,所有其他转换 (bounds) 都会被覆盖。要修复它,您必须创建一个结合了缩放旋转transform

    例子:

    CGAffineTransform scaleTransform = CGAffineTransformMakeScale(0.5, 0.5);
    
    [UIView animateWithDuration:1.0 animations:^
    {
        controlsView.transform = CGAffineTransformRotate(scaleTransform, M_PI/2);
    }];
    

    您需要根据您希望在动画结束时的大小来计算缩放XY 值。您可能还想更改 anchorPoint 属性以设置用于缩放的中心点 (controlsView.layer.anchorPoint)。

    【讨论】:

    • 根据文档,当使用特定的trasnform 时,我应该能够为bounds 属性设置动画。这是frame 属性的文档报告:修改此属性以更改视图相对于其父视图坐标系的大小和位置。 (如果 transform 属性不包含恒等变换,则改为修改 bounds 或 center 属性。)
    【解决方案3】:

    为边界设置动画不会改变它的值。一旦动画结束,它就会恢复到原来的值。

    动画结束后将边界值更改为最终值。麻烦我来解决。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-23
      • 1970-01-01
      相关资源
      最近更新 更多