2014-02-10 144 views
0

我試圖通過點擊一個按鈕時單個UIImageView中的一些圖像循環。按下按鈕後,圖像必須消失0.1秒。 下面的代碼:延遲加載UIImageView中的圖像

int tapCount = 0; 

UIImage *image0 = [UIImage imageNamed:@"0.jpg"]; 
UIImage *image1 = [UIImage imageNamed:@"1.jpg"]; 
UIImage *image2 = [UIImage imageNamed:@"2.jpg"]; 
imagesArray = [[NSArray alloc] initWithObjects:image0, image1, image2, nil]; 


-(IBAction)backgroundButton:(id)sender{ 

    self.myImageView.image = [imagesArray objectAtIndex:tapCount%3]; 
    tapCount++; 
    [self performSelector:@selector(eraseImage) withObject:self afterDelay:0.1]; 
} 

-(void)eraseImage{ 

    self.myImageView.image = nil; 
} 

的問題是,圖像不會出現,直到我已經完成了一個完整的環(在第4 TAP)。 我猜想,我必須初始化UIImageView中的圖像,因爲它需要一定的時間纔會出現在敲擊和圖像之間,並且因爲它在0.1秒後消失......它根本不會顯示。

我試圖加載它們裏面viewDidLoad這樣的:

for(int i = 0; i<[imagesArray count]; i++){ 
    self.myImageView.image = [imagesArray objectAtIndex : i]; 
} 

只是到最後的形象工程加載(在這種情況下,圖像2)。

我是否應該在不同的UIImageView之間循環,而不是在單個UIImageView內循環使用不同的UIImage

任何其他提示?

+0

什麼是圖像,它們有多大?創建一個'UIImage'實際上並不會加載圖像數據(您需要將其渲染到上下文中才能發生)。 – Wain

+0

圖像爲1MB到3MB之間的jpg。 1024x768,因爲必須在iPad中全屏顯示。 我怎樣才能加載它們? – guardabrazo

+0

idk如果這是你如何擁有你的代碼,但我不應該在它的前面;它應該是[imagesArray objectAtIndex:i]; – user2277872

回答

0

我認爲有一個更簡單的方法來實現你要去的動畫。嘗試以下代碼:

-(IBAction)backgroundButton:(id)sender{ 


    [UIView animateWithDuration:0.2 
         delay:nil 
         options:UIViewAnimationCurveEaseIn 
        animations:^{ 
         self.myImageView.image = [imagesArray objectAtIndex:tapCount%3]; 
         self.myImageView.image = nil; 

         } 
      completion:nil 
    ]; 

    tapCount++; 

    if (tapCount == 2) { 
     tapCount = 0; 
    } 

} 
+0

使用此動畫,圖像在0.1秒後不會消失。 我試過添加'完成:^(BOOL完成){self.myImageView。{0} {0} {0}image = nil; '但是這樣,圖像甚至不會出現。 – guardabrazo

+0

因此,用戶點擊後,你想圖像出現0.1秒,然後消失? – Mika

+0

是的!這正是我想要的。 – guardabrazo

2

創建UIImage實際上並不會加載圖像數據(您需要將其渲染到上下文才能發生)。所以,如果你的圖像很大,那麼你可以在它們實際渲染到屏幕之前隱藏它們。您將無法同時在內存中保存許多圖像,但您可以通過創建上下文並將圖像繪製到其中(可以使用CGContextDrawImage在後臺完成)來強制加載圖像數據。

這樣做有幾個第三方代碼位,如this或檢查this discussion

0

我終於來解決這個周圍使用此解決方案:

首先我預裝的所有圖片在後臺線程

-(void)preload:(UIImage *)image{ 

CGImageRef ref = image.CGImage; 
size_t width = CGImageGetWidth(ref); 
size_t height = CGImageGetHeight(ref); 
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB(); 
CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, width * 4, space, kCGBitmapAlphaInfoMask & kCGImageAlphaPremultipliedFirst); 
CGColorSpaceRelease(space); 
CGContextDrawImage(context, CGRectMake(0, 0, width, height), ref); 
CGContextRelease(context); 
} 

然後我執行我在開始時的相同動作:

-(IBAction)backgroundButton:(id)sender{ 

    self.myImageView.image = [imagesArray objectAtIndex:tapCount%3]; 
    tapCount++; 
    [self performSelector:@selector(eraseImage) withObject:self afterDelay:0.1]; 
} 

-(void)eraseImage{ 

    self.myImageView.image = nil; 
}