2015-11-06 17 views
1

我正在構建一個SpriteKit遊戲,利用Facebook圖表檢索朋友(他們也使用該應用程序)的圖像以顯示在關卡選擇屏幕上。水平選擇屏幕之前加載速度相當快,但我注意到需要加載的朋友圖片越多,顯示「水平選擇」屏幕所需的時間就越長。 (屏幕將不會顯示,直到所有的圖像加載。)SpriteKit - 可以使用SDWebImage將Facebook朋友的圖像延遲加載到spriteNodeWithTexture中?

所以我正在探索如何將我的朋友的個人資料圖片加載到SKSpriteNodes以減少等級選擇屏幕加載時的等待時間,圖像在下載後自動顯示。我目前正在嘗試利用SDWebImage,但還沒有看到有關如何將SDWebImage與SpriteKit結合使用的示例。

這是我到目前爲止所做的。 SKSpriteNode將加​​載佔位符圖像沒有問題,但它似乎像Sprite節點不關心在佔位符圖像應用後刷新它的圖像。

UIImageView *friendImage = [[UIImageView alloc] init]; 
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?redirect=true", {FRIEND ID GOES HERE}]]; 
[friendImage sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"user_placeholder_image"]]; 

SKSpriteNode* playerPhoto = [SKSpriteNode spriteNodeWithTexture:[SKTexture textureWithImage:friendImage.image]]; 
[self addChild: playerPhoto]; 

如果任何人有任何關於如何使用SpriteKit完成延遲加載的見解,將不勝感激。

謝謝!

回答

2

在尋找其他方式將圖像「延遲加載」到SKSpriteNode後,我發現了Grand Central Dispatch(GCD)是什麼以及它如何爲我正在嘗試做的工作。我其實不需要使用SDWebImage。

這裏是我用來獲取完美的結果代碼:

// init the player photo sprite node - make sure to use "__block" so you can use the playerPhoto object inside the block that follows 
__block SKSpriteNode* playerPhoto = [[SKSpriteNode alloc] init]; 

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
dispatch_async(queue, ^{ 
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?redirect=true", {FRIEND FB ID GOES HERE}]]]; 
    UIImage *image = [UIImage imageWithData:data]; 
    dispatch_async(dispatch_get_main_queue(), ^{ 

     // update player photo texture after image was downloaded 
     playerPhoto.texture = [SKTexture textureWithImage:image]; 
     NSLog(@"fb image downloaded and applied!"); 
    }); 
}); 

// use a placeholder image while fb image downloads 
playerPhoto = [SKSpriteNode spriteNodeWithTexture:[SKTexture textureWithImage:[UIImage imageNamed:@"user_placeholder_image"]]]; 

希望這可以幫助別人的未來。 :)