Ios中CATransform3D的一点使用心得。

来源:互联网 发布:数据流量英语 编辑:程序博客网 时间:2024/05/22 14:13

    最近项目中有个绕y轴左右摆动UIView的需求。首先想到了使用CATransform3D来做旋转。但是使用过程中碰到了如下两个问题。

   问题1:旋转之后,目标View只能看到一半的UI,比如绕y轴旋转只能看到左半边或者右半边。

   问题2:摆动的动画,给人感觉总是向一边摆动(一直向左边或者右边)代码如下:

     CATransform3D rotationTransform = CATransform3DIdentity;
        rotationTransform = CATransform3DRotate(rotationTransform, 0.25 * M_PI_2, 0.0f, 1.0f, 0.0f);
        weakSelf.viewHightScoreAvatar.layer.transform = rotationTransform;
        
        [UIView animateWithDuration:2.0 delay:0 options: UIViewAnimationOptionRepeat |UIViewAnimationOptionAutoreverse  animations:^{
            CATransform3D rotationTransform2 = CATransform3DIdentity;

            rotationTransform2 = CATransform3DRotate(rotationTransform2, -0.25* M_PI_2, 0.0f, 1.0f, 0.0f);
            weakSelf.viewHightScoreAvatar.layer.transform = rotationTransform2;
            
        } completion:^(BOOL finished) {
           
        }];

   经过多次查找资料跟不断尝试终于发现了问题所在,解决方法如下:

   对于问题1:可以通过设置CALayer的zPosition来解决,zPosition表示UIView在UI渲染的时候,在屏幕上的层级,zPosition越大在越上面。

   对于问题2:可以通过设置CATransform3D的m34来解决,m34表示透视效果,默认值是0(1/D),表示的是无穷远( D无穷大)。当D越小,也就是m34越接近1,透视效果越明显。

   修改后的代码如下:

CATransform3D rotationTransform = CATransform3DIdentity;
        rotationTransform.m34 = -1.0f/200.0f;//注意这里要在CATransform3DRotate前调用,否则看不效果。
        rotationTransform = CATransform3DRotate(rotationTransform, 0.25 * M_PI_2, 0.0f, 1.0f, 0.0f);
        weakSelf.viewHightScoreAvatar.layer.transform = rotationTransform;
        weakSelf.viewHightScoreAvatar.layer.zPosition = 100;
        
        [UIView animateWithDuration:2.0 delay:0 options: UIViewAnimationOptionRepeat |UIViewAnimationOptionAutoreverse  animations:^{
            CATransform3D rotationTransform2 = CATransform3DIdentity;
            rotationTransform2.m34 = -1.0f/200.0f;
            rotationTransform2 = CATransform3DRotate(rotationTransform2, -0.25* M_PI_2, 0.0f, 1.0f, 0.0f);
            weakSelf.viewHightScoreAvatar.layer.transform = rotationTransform2;
            
            weakSelf.viewHightScoreAvatar.layer.zPosition = 100;
            
        } completion:^(BOOL finished) {
           
            
        }];


0 0
原创粉丝点击