我有一个自定义的 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/