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

时间:2017-01-02 19:43:04

标签: 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 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获得了加速度计值并使用它来改变图像的不透明度,但我无法实时显示结果,我该怎么做?

1 个答案:

答案 0 :(得分:1)

问题是在后台线程上调用了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更改都将正常工作。