使用线程在图像视图中分配图像



我有以下代码在图像视图中的两个图像之间切换。我没有使用 GCD,因为此代码是已以这种方式编码的现有系统的一部分。

- (void)updateimage { 
dispatch_async(dispatch_get_main_queue(), ^{
        if (self.fileno % 2 == 0) {
            self.imageViewTest.image = [UIImage imageNamed:@"Image7.png"];
        }
        else {
           self.imageViewTest.image = [UIImage imageNamed:@"Image8.png"];
        }
       [self.imageViewTest setNeedsDisplay];
        self.filenolabel.text = [NSString stringWithFormat:@"%d", self.fileno];
    });
}
- (void)calculateFileNo {
while (1) {
    self.fileno ++;
    sleep(1);
    [self updateimage];
 }
}
- (void)viewDidLoad {
     [super viewDidLoad];
     self.detectionThread = [[NSThread alloc]initWithTarget:self  selector:@selector(calculateFileNo) object:nil] ;
    [self.detectionThread setName:@"NewThread"];
    [self.detectionThread start];
 }

文件标签为每个循环显示正确的编号。但有时图像无法正确切换。在循环的 2 或 3 次迭代中显示相同的图像。我希望每次迭代都切换图像。请帮忙。提前致谢

增量位置是一个问题 'self.fileno ++' ->将其移动到调度程序。

- (void)updateimage { 
dispatch_async(dispatch_get_main_queue(), ^{
        if (self.fileno % 2 == 0) {
            self.imageViewTest.image = [UIImage imageNamed:@"Image7.png"];
        }
        else {
           self.imageViewTest.image = [UIImage imageNamed:@"Image8.png"];
        }
       [self.imageViewTest setNeedsDisplay];
        self.filenolabel.text = [NSString stringWithFormat:@"%d", self.fileno];
    self.fileno ++;
    });
}
- (void)calculateFileNo {
while (1) {
    sleep(1);
    [self updateimage];
 }
}

在主线程内增加文件。

     self.fileno++;

只有在UImageView的子类中覆盖drawRect时,才应该调用setNeedsDisplay,该子类基本上是在屏幕上绘制某些内容的自定义视图,例如线条,图像或矩形等形状。

因此,当您更改此绘图所依赖的几个变量并为了使视图表示该更改时,您应该调用setNeedsDisplay,您需要调用此方法,该方法将在内部调用drawRect并重新绘制组件。

当您更改图像的图像视图或更改任何子视图时,需要调用此方法。

    - (void)updateimage {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.fileno % 2 == 0) {
                self.imageView.image = [UIImage imageNamed:@"Image7.png"];
            }
            else {
                self.imageView.image = [UIImage imageNamed:@"Image8.png"];
            }
            [self.imageView setNeedsDisplay];
            self.fileno ++; // Increament your file no inside the main thread.
            self.textView.text = [NSString stringWithFormat:@"%d", self.fileno];
        });
    }

最新更新