iOS:从 NSThread 制作图片旋转动画

标签 ios objective-c rotation

我试图让图片围绕其中心连续旋转。我创建一个线程,它调用委托(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:

中的这一行来强制 UI 在主线程上更新
_myImageView.transform = CGAffineTransformMakeRotation(newRad);

进入下面的 block ,像这样:

dispatch_async(dispatch_get_main_queue(), ^{

    _myImageView.transform = CGAffineTransformMakeRotation(newRad);

});

关于iOS:从 NSThread 制作图片旋转动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26847934/

相关文章:

objective-c - iPad Retina 显示器的 XCode 坐标

actionscript-3 - AS3 围绕其中心点旋转对象

c - 旋转 90 度二维字符数组

ios - 按钮的框架没有改变

iphone - 创建自定义动画属性

ios - 从单独的 View 中重新加载 UIWebView

objective-c - Objective-C 中的 int 是否有默认值 1?

rotation - 在 Canvas 中多次旋转单行

ios - 如何最好地将巨大的 .sqlite 数据库移动到旧的低内存 iOS 设备上的新目录?

objective-c - iOS 面朝上方向问题