Objective c 如何在IOS中实时更改图像不透明度

Objective c 如何在IOS中实时更改图像不透明度,objective-c,Objective C,我是ios的初学者,我想通过旋转iphone改变图像的不透明度,并在视图上实时显示它 #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a

我是ios的初学者,我想通过旋转iphone改变图像的不透明度,并在视图上实时显示它

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController


- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.motionManager = [[CMMotionManager alloc]init];
self.motionManager.accelerometerUpdateInterval = 0.1;
if([self.motionManager isAccelerometerAvailable]){

    [self.motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error){
        if(error){
            [self.motionManager stopAccelerometerUpdates];
        }else{

            accX = floor(accelerometerData.acceleration.x * 100)/100;
            accY = floor(accelerometerData.acceleration.y * 100)/100;
            accZ = floor(accelerometerData.acceleration.z * 100)/100;
            NSLog(@"x = %f", accX);
            NSLog(@"y = %f", accY);
            NSLog(@"z = %f", accZ);

        }
    }];
}else{
    NSLog(@"Gyroscope is not available.");
}
NSBundle *bundle = [NSBundle mainBundle];
self.solder = [[UIImage alloc]initWithContentsOfFile:[bundle     
pathForResource:@"solder" ofType:@"jpg"]];
self.woman= [[UIImage alloc]initWithContentsOfFile:[bundle 
pathForResource:@"woman" ofType:@"jpg"]];

   self.solderImage.alpha = accX;

   self.solderImage.image = self.solder;


}


- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
[self.motionManager stopGyroUpdates];
// Dispose of any resources that can be recreated.
}

@end

我从iphone获得了加速计值,并使用它来更改图像的不透明度,但我无法实时显示结果,我如何才能做到这一点?

问题是在后台线程上调用了
startAccelerometerUpdatesToQueue:withHandler
的处理程序块,禁止在后台线程上进行UI更改,这将导致未定义的行为

一种解决方案是更新调度块内部的alpha:

accX = floor(accelerometerData.acceleration.x * 100)/100;
accY = floor(accelerometerData.acceleration.y * 100)/100;
accZ = floor(accelerometerData.acceleration.z * 100)/100;

dispatch_async(dispatch_get_main_queue(), ^{
    self.solderImage.alpha = accX;
});
分派块将块内的指令添加到主线程上的队列中。这样,它将在主线程上运行,任何UI更改都将正常工作