How do i rotate a CALayer around a diagonal line?

前端 未结 3 1750
旧巷少年郎
旧巷少年郎 2021-01-31 21:42

I\'m trying to implement a flip animation to be used in board game like iPhone-application. The animation is supposed to look like a game piece that rotates and changes to the c

3条回答
  •  一个人的身影
    2021-01-31 22:06

    Here is a Xamarin iOS example I use to flap the corner of a square button, like a dog ear (easily ported to obj-c):

    Method 1: use a rotation animation with 1 for both x and y axes (examples in Xamarin.iOS, but easily portable to obj-c):

    // add to the UIView subclass you wish to rotate, where necessary
    AnimateNotify(0.10, 0, UIViewAnimationOptions.CurveEaseOut | UIViewAnimationOptions.AllowUserInteraction | UIViewAnimationOptions.BeginFromCurrentState, () =>
    {
        // note the final 3 params indicate "rotate around x&y axes, but not z"
        var transf = CATransform3D.MakeRotation(-1 * (nfloat)Math.PI / 4, 1, 1, 0);
        transf.m34 = 1.0f / -500;
        Layer.Transform = transf;
    }, null);
    

    Method 2: just add an x-axis rotation, and y-axis rotation to a CAAnimationGroup so they run at the same time:

    // add to the UIView subclass you wish to rotate, where necessary
    AnimateNotify(1.0, 0, UIViewAnimationOptions.CurveEaseOut | UIViewAnimationOptions.AllowUserInteraction | UIViewAnimationOptions.BeginFromCurrentState, () =>
    {
        nfloat angleTo = -1 * (nfloat)Math.PI / 4;
        nfloat angleFrom = 0.0f ;
        string animKey = "rotate";
    
        // y-axis rotation
        var anim = new CABasicAnimation();
        anim.KeyPath = "transform.rotation.y";
        anim.AutoReverses = false;
        anim.Duration = 0.1f;
        anim.From = new NSNumber(angleFrom);
        anim.To = new NSNumber(angleTo);
    
        // x-axis rotation
        var animX = new CABasicAnimation();
        animX.KeyPath = "transform.rotation.x";
        animX.AutoReverses = false;
        animX.Duration = 0.1f;
        animX.From = new NSNumber(angleFrom);
        animX.To = new NSNumber(angleTo);
    
        // add both rotations to a group, to run simultaneously
        var animGroup = new CAAnimationGroup();
        animGroup.Duration = 0.1f;
        animGroup.AutoReverses = false;
        animGroup.Animations = new CAAnimation[] {anim, animX};
        Layer.AddAnimation(animGroup, animKey);
    
        // add perspective
        var transf = CATransform3D.Identity;
        transf.m34 = 1.0f / 500;
        Layer.Transform = transf;
    
    }, null);
    

提交回复
热议问题