【问题标题】:changing between multiple images for an UIImage in xcode在 xcode 中为 UIImage 更改多个图像
【发布时间】:2011-12-11 06:46:09
【问题描述】:

一直在开发一个应用程序并一直在研究此处提供的问题,但没有找到类似的东西来解决我的问题。

我有一个包含 4 个图像的数组设置,每次按顺序触摸图像时,我都会尝试更改为不同的图像,然后在显示最后一个图像后返回到第一个图像。

例如:image1 "touch" => image2 "touch" => image3 "touch" image4 "touch" => image1.....

除非“触摸”,否则图像不会改变。

我的数组设置为:

    -(void) viewDidLoad {
        imageArray = [[NSArray alloc] initWithObjects:
                      [UIImage imageNamed:@"image1.png"],
                      [UIImage imageNamed:@"image2.png"],
                      [UIImage imageNamed:@"image3.png"],
                      [UIImage imageNamed:@"image4.png"],
                      nil];

然后我用以下内容显示第一张图片:

    imageView.image = [imageArray objectAtIndex:0];

然后,我可以使用以下代码在两个图像之间成功切换:

    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
       UITouch *touch = [[event allTouches] anyObject];
       NSLog(@"'Touches Began");

       if ([touch view] == imageView) {
           imageView.image = [imageArray objectAtIndex:1];
           NSLog(@"Image touched and changed");
       }

现在,因为我希望 imageView 显示两个以上的更改,所以我尝试在 for 循环中使用 if 语句,但没有成功:

    int touchCount = 0;
    for (touchCount = 1; touchCount < 4; touchCount++) {
        if ((touchCount < 4) && ([touch view] == imageView)) {
            imageView.image = [imageArray objectAtIndex:touchCount];
            NSLog(@"Touch Count = %d", touchCount);
        }
    }

运行时,调试器显示“Touch Count = 0”,然后崩溃并返回主屏幕。有人可以帮忙解决这个问题吗?我的概念错了吗?

【问题讨论】:

  • 崩溃时的日志是什么意思?
  • 您的 for 循环,如果它没有崩溃,将简单地快速连续显示每个图像。您将在少量图像中旋转并不是对循环结构的调用。这只是保持接下来要出现的图像。你可以有一个随机数生成器来选择它,或者其他一些算法。您的代码需要做的是决定接下来应该显示什么图像,然后将该图像交出。 JRTurton 对旋转算法给出了很好的答案。

标签: iphone objective-c xcode cocoa-touch uiimage


【解决方案1】:

有一个整数作为实例变量,用于存储正在显示的图像。在 viewDidLoad 上将此设置为 0。

当在图像视图上注册触摸时,递增整数。如果该值等于图像数组的计数,请将其设置回 0。

将图像设置为由整数值指示的图像数组的元素:

// touch registered on image
currentImage++;
if (currentImage == [imageArray count])
    currentImage = 0;

imageView.image = [imageArray objectAtIndex:currentImage];

【讨论】:

  • 感谢大家的帮助!现在效果很好。我的印象是我需要某种循环来促进继续,忘记了 xcode 本身已经以循环方式运行,直到触发。另外,我想指出,起初我使用“NSInteger touchCount”初始化touchCount,但它一直在崩溃。我将其视为“指针”而不是常规整数。取出“”解决了所有问题,因为它现在是一个常规整数。我是什么菜鸟!!我还有很多工作要做。
  • 我的意思是在上面的评论中加上“NSInteger touchCount”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-30
  • 1970-01-01
  • 2011-06-25
  • 1970-01-01
相关资源
最近更新 更多