我试图让图片围绕其中心连续旋转。我创建一个线程,它调用委托(delegate)方法来更新图片的旋转。我完全跑过去,但旋转没有改变。 旋转设置为
_myImageView.transform = CGAffineTransformMakeRotation(newRad);
当我放
_myImageView.transform = CGAffineTransformMakeRotation(M_PI_2);
进入viewDidLoad方法,图像被变换90°。 如果下面的代码被执行,它不会做任何事情,尽管 hasUpdated 方法被正确调用。变量 newRad 包含有效值。 那么图像不旋转的原因可能是什么? 感谢您的帮助。
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a
[self setDelegate:self];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)hasUpdated:(int)x{
// Convert Degree to Radian and move the needle
float newRad = x * M_PI / 180.0f;
_myImageView.transform = CGAffineTransformMakeRotation(newRad);
}
- (IBAction)myTest:(id)sender {
NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(myLoop) object:nil];
[myThread start];
}
- (void) myLoop
{
int x = 1;
while(true)
{
x++;
if(x==360)
{
x = 1;
}
sleep(1);
[self.delegate hasUpdated:x];
}
}
最佳答案
由于您正尝试从 hasUpdated:
方法更新 UI,该方法已从 myTest:
方法中调用,该方法又作为选择器调用由 IBAction
触发的 NSThread
,您实际上是在尝试从这个新的 NSThread
更新 UI;但您只能从应用的主线程更新应用的用户界面。
为了维护这个新线程,同时在其中的一个方法期间仍然更新 UI,您可以通过粘贴 hasUpdated:
_myImageView.transform = CGAffineTransformMakeRotation(newRad);
进入下面的 block ,像这样:
dispatch_async(dispatch_get_main_queue(), ^{
_myImageView.transform = CGAffineTransformMakeRotation(newRad);
});
关于iOS:从 NSThread 制作图片旋转动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26847934/