ios - 使用 UIBezierPaths 反转自定义 UIView 上的 CGAffineTransform 旋转

标签 ios uiviewanimation cgaffinetransform uibezierpath

我有一个自定义的 UIView。它初始化了两个矩形的 UIBezierPaths,并且在 drawRect 中它只是填充了这两个路径。

该 View 放置在按钮上。单击按钮时,会在 animateWithDuration block 内对其应用旋转:

icon.transform = CGAffineTransformMakeRotation(M_PI*-0.25);

这很好用。

当再次单击按钮时,我试图使 View 旋转回其原始方向(反转旋转)。我尝试过:

icon.transform = CGAffineTransformInvert(icon.transform);
icon.transform = CGAffineTransformMakeRotation(M_PI*0.25);
icon.transform = CGAffineTransformIdentity;

...以及许多其他变体,但它们似乎都不起作用。相反, View 会被扭曲,直到不再可见——有点拉伸(stretch)到什么都没有。有时,重新应用第一个变换会将其恢复,但使用其他反转则不会。

我做错了什么?

最佳答案

在ios中,变换总是相对的,因此一旦变换完成,下一个变换应该相对于上一个变换。您只需更改 View 的框架并在单击第二次按钮时将其恢复正常。即使单击,您也必须恢复框架。实现以下代码。如果您觉得合适,您可以使用 block 级代码,因为它是新规范。

int noOfClicks = 0;

-(IBAction)yourBtnAction:(id)sender
{
    noOfClicks++;

    if(noOfClicks %2 != 0)
    {
        [UIView beginAnimations:@"Rotate" context:nil];
        [UIView setAnimationDuration:1.0];
        [UIView setAnimationDelegate:self];
        CGRect frame=yourView.frame;
        frame.origin.y+=20;
        yourview.frame=frame;
        [UIView commitAnimations];
    }
    else
    {
        [UIView beginAnimations:@"Rotate" context:nil];
        [UIView setAnimationDuration:1.0];
        [UIView setAnimationDelegate:self];
        CGRect frame=yourView.frame;
        frame.origin.y-=20;
        yourview.frame=frame;
        [UIView commitAnimations];
    }
}

如果您不想进行如此多的更改,您可以使用以下命令来恢复,但采用相同的逻辑:

[UIView beginAnimations:@"Rotate back" context:nil];
[UIView setAnimationDuration:1.0];

yourView.transform = CGAffineTransformIdentity;

[UIView commitAnimations];

关于ios - 使用 UIBezierPaths 反转自定义 UIView 上的 CGAffineTransform 旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10557849/

相关文章:

iphone - NSInputStream 使用本地文件,而不是从服务器拉取的文件

iphone - NSAffinetransform 和 CGAffinetransform 之间的区别

objective-c - 从 uiimageview 获取旋转后的图像

ios - 使用约束旋转 View - Swift

ios - 如何为不同的 iOS 应用配置文件包含不同的 plist

iphone - 供应商需要的 SKU 编号

ios - Xcode 7.0.1 (7A1001) 调试器 "Unable to read data"

iphone - 我如何等到另一个类中的动画完成后再继续?

ios - 圆形 UIView 上的 CGAffineTransformMakeScale 动画为正方形

ios - UITapGestureRecognizer 不响应动画 subview