从之前的几个 StackOverFlow问题和 github CA360上的这个示例中,我设法模拟了一张翻转卡片,“正面”有图像,背面有文字。然而,卡片背面的文字是颠倒的,我只让它水平居中。如何正确定位文本并将其垂直居中放在卡片上?
卡片正面:
卡片背面(如何垂直定位和居中文本?):
[更新]
我将顶层的不透明度设置为 0.5,然后我想到“预翻转”背面层,这样当实际翻转发生时,它就会将其重置为正常状态。
我的“预翻转”看起来像这样:
cardBack.transform = CATransform3DMakeRotation(M_PI, 1.0f, 0.0f, 0.0f); // Pre-flip card
现在我只需要找到一种内置的垂直设置方法或者很难做到……距离的一半……字体高度……加上……
设置有 2 层的卡片容器(参考):
-(无效)加载视图{ UIView *myView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; myView.backgroundColor = [UIColor whiteColor]; self.view = myView; cardContainer = [CATransformLayer 层]; cardContainer.frame = CGRectMake(300, 250, 200, 150); CALayer *cardFront = [CALayer 层]; cardFront.frame = cardContainer.bounds; cardFront.zPosition = 5; // 高于卡片背面的zPosition cardFront.contents = (id)[UIImage imageNamed:@"Ben"].CGImage; cardFront.opacity = 0.5; [cardContainer addSublayer:cardFront]; /* https://stackoverflow.com/questions/2209734/add-text-to-calayer */ CATextLayer *cardBack = [CATextLayer 层]; cardBack.string = @"你好"; cardBack.frame = cardContainer.bounds; cardBack.zPosition = 4; cardBack.backgroundColor = [[UIColor grayColor] CGColor]; cardBack.alignmentMode = kCAAlignmentCenter; CFTypeRef *font = (CFTypeRef *)CTFontCreateWithName(CFSTR("Times"), 48, NULL); cardBack.font = 字体; [cardContainer addSublayer: cardBack]; [self.view.layer addSublayer:cardContainer]; }
借用另一个 SOF 问题的代码来翻转卡片:
-(无效)翻转卡{ // [self.flipTimer 无效]; // 如果(翻转){ // 返回; // } NSLog(@"Count=%d", count); id 动画块 = ^{ // self.backView.alpha = 1.0f; // self.frontView.alpha = 0.0f; // [self bringSubviewToFront:self.frontView]; //翻转=是; NSLog(@"正在翻转..."); CALayer *layer = cardContainer; CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity; 旋转和透视变换.m34 = 1.0 / 500; 如果(计数 == 0){ rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, M_PI, 1.0f, 0.0f, 0.0f); } else { // 将其翻转回图像 rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 0.0f, 0.0f, 1.0f, 1.0f); } layer.transform = 旋转和透视变换; }; 计数 = (计数 + 1) % 2; [UIView animateWithDuration:1.25 延迟:0.0 选项: UIViewAnimationCurveEaseInOut 动画:动画块 完成:无]; }