使用CGAffineTransformScale自定义UIView缩放

4

我正在学习iOS开发,作为教育过程的一部分,我创建了一个自定义的UIView,它使用drawRect来绘制其内容(基于Core Graphics和UIBezierPath)。一切正常,视图是动态的,并根据其宽度/高度呈现其内容。现在我想添加溶解动画,看起来像从100%缩放到0%。我编写了以下代码来实现:

[UIView animateWithDuration:1 delay:0
                options: UIViewAnimationOptionBeginFromCurrentState
             animations: ^{
     for (CardView *cardView in self.cardsViews) {
         cardView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.01, 0.01);

     }} completion:nil];

然而,这段代码并不能将我的视图从100%缩放到0%。它只会使卡片消失(最多)。我尝试了许多缩放的方法,但是我迄今为止达到的唯一效果是从0%缩放到100%。这个视图可以完美地实现,但不是反向缩放...另外,即使我尝试应用非动画的变换,如下所示,它也不能进行缩放:

cardView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.5, 0.5);

我看到我的视图外观有一点变化,但肯定没有缩放到50%。当我尝试将完全相同的动画逻辑应用于UILabel时,它完美地工作!开发自定义UIView时,我错过了什么?为什么缩放视图可能会失效?
非常感谢提前!更新#1:这段代码使我的视图恰好变大了两倍,然后将其缩小到原始大小:
[UIView animateWithDuration:5 delay:0
                    options: UIViewAnimationOptionBeginFromCurrentState
                 animations: ^{
         for (CardView *cardView in self.cardsViews) {
             cardView.transform = CGAffineTransformMakeScale(0.5, 0.5);
         }
    } completion:nil];

你尝试过添加一个动画选项 UIViewAnimationOptionAllowAnimatedContent 吗? - Rafał Sroka
谢谢。是的,我已经尝试过了。没有成功。而且,即使没有动画,我的自定义视图也不会缩放... - Serzhas
@Serzhas 你有在这方面取得任何进展吗? - Matt Mc
是的,我记得我当时解决了这个问题,但那已经很久以前了,而且我已经不再从事那个项目了,所以我无法检查代码...抱歉。 - Serzhas
3个回答

6
使用CGAffineTransformScale将100%缩放为0%非常简单:
cardView.view.transform =CGAffineTransformScale(CGAffineTransformIdentity, 1.1, 1.1);

[UIView animateWithDuration:0.3/1.5 animations:^{
        cardView.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.1, 0.1);
    } completion:^(BOOL finished)
    {
              NSLog(@" Animation complet Block");
    }];

1
您可以尝试将视图的contentMode设置为UIViewContentModeRedraw,并在animateWithDuration方法中添加另一个动画选项 - UIViewAnimationOptionAllowAnimatedContent

谢谢!我会尝试并回报。 - Serzhas
不好意思,这并没有帮助到我...我的视图已经有了正确的contentMode,添加动画选项也没有任何区别。请注意,即使没有动画,我的视图也不会缩放。仅仅尝试将其缩小到原始大小的50%是没有用的... :/ - Serzhas

1

Swift从120%缩放到100%:

logoView.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
UIView.animate(withDuration: 0.55, delay: 0.1, options: [.curveEaseOut], animations: {
    self.logoView.transform = .identity
    self.view.layoutIfNeeded()
}, completion: { _ in
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接