CGRectMake的问题

时间:2011-04-13 01:05:30

标签: iphone objective-c cocoa-touch

我一直在尝试在iPhone上创建16x16图像的网格。

- (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具有我想要的值,所以值的赋值工作正常。这是怎么回事?

3 个答案:

答案 0 :(得分:3)

在NSLog中将xLocation转换为int肯定会有效,但您也可以使用:

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

有一系列NSStringFromXXX辅助函数可以随时派上用场。

答案 1 :(得分:2)

第一列的xLocation为0,每列增加xLocation,但每个新列的y坐标不会重置为0。它只是基于i不断增加。因此,第二个向前的列只是在右侧xLocation的屏幕外,但是y值很高。

尝试将imageRect计算更改为:

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

答案 2 :(得分:1)

%d没有正确显示浮动。使用%f或将xLocation转换为int:

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

您还可以通过每次计算来简化xLocation计算可读性,例如

16 * (i / 30)

现代处理器的开销很小。