将CALayers组合并作为子视图翻转到CATransformLayer

时间:2012-11-29 22:53:17

标签: catransform3d catransformlayer

基于早期的stackoverflow建议,我正在尝试使用添加到CATransformLayer的CALayers创建一张扑克牌。我们的想法是创建前后CALayers并将它们组合在CATransformLayer中,然后可以旋转,翻转等,并自动显示正确的一面。下面是尝试创建一张绿色正面和红色背面的单张卡的示例代码。

红色背面绕Y轴翻转,使其背向绿色正面。绿色前面的calayer有一个比红背更“Z”的位置。

当我进行转换时,我只是看到卡片处于非翻转状态。我在这里错了什么想法?

#define DEGREES_TO_RADIANS(angle) (angle * M_PI / 180.0)

- (void)viewDidLoad
{
    [super viewDidLoad];

    CATransformLayer *cardContainer = [CATransformLayer layer];

    cardContainer.bounds = CGRectMake(0,0, 150,200);


    CALayer *cardFront  = [CALayer layer];
    cardFront.frame     = cardContainer.bounds;

    cardFront.backgroundColor = [UIColor greenColor].CGColor;
    cardFront.borderColor = [UIColor blackColor].CGColor;
    cardFront.borderWidth = 2.0;
    cardFront.cornerRadius = 30.0;
    cardFront.zPosition = 2; // Put front of card on top relative to back of card
    cardFront.doubleSided = NO;
    [cardContainer addSublayer:cardFront];

    CALayer *cardBack  = [CALayer layer];
    cardBack.frame     = cardContainer.bounds;
    cardBack.backgroundColor = [UIColor redColor].CGColor;
    cardBack.zPosition = 1;
    cardBack.doubleSided = NO;

    // Flip cardBack image so it is facing outward and visible when flipped
    cardBack.transform = CATransform3DMakeRotation(DEGREES_TO_RADIANS(180),0.0,1.0,0.0);
    [cardContainer addSublayer:cardBack];

    UIView* cardView = [[UIView alloc] initWithFrame:cardContainer.bounds];
    cardView.center = CGPointMake(self.view.center.x, self.view.center.y);
    [cardView.layer addSublayer:cardContainer];
    [self.view addSubview:cardView];

    // Show the card flipped over (desired the red side to be showing, but instead shows green)
    cardView.layer.transform = CATransform3DMakeRotation(DEGREES_TO_RADIANS(180),0.0,1.0,0.0);

}

1 个答案:

答案 0 :(得分:1)

发现问题,您必须将变换应用于sublayerTransform属性,如:

cardView.layer.sublayerTransform = ...