Question: How do I change image opacity in real time in IOS

Question

How do I change image opacity in real time in IOS

Answers 1
Added at 2017-01-02 20:01
Tags
Question

I'm a beginner in ios,I want to change the opacity of the image by rotating iphone and display the it on the view in real time

#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

I got the accelerometer value from iphone and use it to change the opacity of the image but I can't display the result in real time,how can I do this?

Answers
nr: #1 dodano: 2017-01-02 20:01

The issue is that the handler block for startAccelerometerUpdatesToQueue:withHandler is called on a background thread, and making UI changes on the background thread is prohibited and will cause undefined behaviour.

One solution would be to update the alpha inside of a dispatch block:

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;
});

A dispatch block adds the instructions inside of the block to the queue on the main thread. That way, it'll be run on the main thread and any UI changes will work correctly.

Source Show
◀ Wstecz