2011-04-13 158 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的助手功能,不时派上用场。