How do i rotate a CALayer around a diagonal line?

前端 未结 3 1791
旧巷少年郎
旧巷少年郎 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:12

    you can fake it this way: create an affine transform that collapse the layer along it's diagonal:

    A-----B           B
    |     |          /
    |     |   ->   A&D
    |     |        /
    C-----D       C
    

    change the image, and trasform the CALayer back in another animation. This will create the illusion of the layer rotating around its diagonal.

    the matrix for that should be if I remember math correctly:

    0.5 0.5 0
    0.5 0.5 0
    0   0   1
    

    Update: ok, CA doen't really likes to use degenerate transforms, but you can approximate it this way:

    CGAffineTransform t1 = CGAffineTransformMakeRotation(M_PI/4.0f);
    CGAffineTransform t2 = CGAffineTransformScale(t1, 0.001f, 1.0f);
    CGAffineTransform t3 = CGAffineTransformRotate(t2,-M_PI/4.0f);  
    

    in my tests on the simulator there still was a problem because the rotations happens faster than te translation so with a solid black square the effect was a bit weird. I suppose that if you have a centered sprite with transparent area around it the effect will be close to what expected. You can then tweak the value of the t3 matrix to see if you get a more appealing result.

    after more research, it appears that one should animate it's own transition via keyframes to obtaim the maximum control of the transition itself. say you were to display this animation in a second, you should make ten matrix to be shown at each tenth of a second withouot interpolation using kCAAnimationDiscrete; those matrix can be generated via the code below:

    CGAffineTransform t1 = CGAffineTransformMakeRotation(M_PI/4.0f);
    CGAffineTransform t2 = CGAffineTransformScale(t1, animationStepValue, 1.0f);
    CGAffineTransform t3 = CGAffineTransformRotate(t2,-M_PI/4.0f);  
    

    where animationStepValue for ech of the keyFrame is taken from this progression:

    {1 0.7 0.5 0.3 0.1 0.3 0.5 0.7 1}
    

    that is: you're generating ten different transformation matrix (actually 9), pushing them as keyframes to be shown at each tenth of a second, and then using the "don't interpolate" parameter. you can tweak the animation number for balancing smoothness and performance*

    *sorry for possible errors, this last part was written without a spellchecker.

提交回复
热议问题