2011-04-13 155 views
1

我一直在試圖在iPhone上創建16x16圖像的網格。麻煩與CGRectMake

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    int xLocation = 0; 

    for (int i=0; i <= 619; i++) { 


     if (((i % 30) == 0) && i != 0) { //if at end of column (30th row), moves x over 16 px to next column 
      xLocation += 16; 
     } 
     else {;} 


    CGRect imageRect = CGRectMake(xLocation, (16*i), 16, 16); 
    UIImageView *image = [[UIImageView alloc] initWithFrame:imageRect]; 
    [image setImage:[UIImage imageNamed:@"Untitled-1.png"]]; 
    [image setOpaque:YES]; 

     NSLog(@"%d", xLocation); 


    [self.view addSubview:image]; 
    [image release]; 
    } 

問題是int xLocation。出於某種原因,CGRectMake在x座標槽中使用0而不是xLocation。我說「而不是」,因爲下面的NSLog顯示xLocation具有我想要的值,所以值的賦值工作正常。這裏發生了什麼?

回答

2

對於第一列,xLocation爲0,對於每列都增加,但對於每個新列,y座標不會重置爲0。它只是基於我不斷增加。因此,第二個以後的列僅在xLocation右側的屏幕外顯示,而y值很高。

嘗試改變imageRect計算:

CGRect imageRect = CGRectMake(xLocation, (16*(i % 30)), 16, 16); 
+0

非常感謝,我一直專注於xLocation,這實際上不是問題所在。 – Regan 2011-04-13 03:24:41

1

%d沒有正確顯示浮點數。使用%F或轉換xLocation爲int:

NSLog(@"%d", (int)xLocation); 

您還可以通過每一次計算它,像

16 * (i/30) 

的開銷是在現代處理器的最小簡化xLocation計算可讀性。

+0

'xLocation'的類型是'int'。 – 2011-04-13 02:23:45

3

鑄造xLocation在您的NSLog一個int肯定會工作,但你也可以使用:

NSLog(@"imageRect %@", NSStringFromCGRect(imageRect)); 

有一個全系列NSStringFromXXX的助手功能,不時派上用場。