2014-06-05 32 views
0

所以我有幾個圖像從0.png到9.png他們將用於得分。 現在我想根據當前得分顯示圖像。我可以這樣做:指定整數變量圖像

scoreImage = [UIImage imageNamed:[NSString stringWithFormat:@"%d.png", score]]; 

上面的代碼意味着我必須創建無限數量的圖像來覆蓋分數。 有沒有更有效的方法來做到這一點?僅使用10個圖像的每一位例如0.png 1.png 2.png ... 9.png

預先感謝

+0

難道你不會做 scoreImage = [UIImage imageNamed:[NSString stringWithFormat:@「%d.png」,score%100]] ?? – vent

回答

1

MOST有效的方式來做到這一點是使用顯示文本視圖對象直接,就像一個UILabel。然後,您可以簡單地將其字體,大小和樣式設置爲所需的值,並將其文本設置爲所需的值。

你可以製作一個只包含數字的自定義字體,並使用它。我從來沒有創建過自定義字體,但我知道這是可能的。

如果失敗了,您可以創建一個包含4個UIImageView對象的自定義ScoreView類。它會有一個整數屬性分數,當您設置分數值時,它會將正確的數字圖像安裝到不同的組件圖像視圖中。

的代碼來計算數字值可能是這樣的:

int score = 7596; 
int remainder = score; 

int thousandsValue = remainder/1000; 
remainder -= thousandsValue*1000; 

int hundredsValue = remainder /100; 
remainder -= hundredsValue*100; 

int tensValue = remainder/10; 
int onesValue = remainder % 10; 

NSLog(
     @"For %d, thousandsValue = %d, hundredsValue = %d, tensValue = %d, onesValue = %d", 
     score, 
     thousandsValue, 
     hundredsValue, 
     tensValue, 
     onesValue 
    ); 

然後使用這些值來構建圖像文件名您的千位,百位,十位和個位數字圖像視圖。

最後,加載並將圖像安裝到每個imageView中。