我一直在尝试在16x16图像的iPhone上创建一个网格。
- (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具有我想要的值,所以值的赋值工作正常。这里发生什么事情?
发布于 2011-04-13 10:36:14
对于第一列,xLocation是0,并且对于每一列都在增加,但是对于每一新列,y坐标不会被重置为0。它只是在i的基础上不断增加,所以从第二个开始的列就在屏幕外的右边的xLocation处,但是y值很高。
尝试将imageRect计算更改为:
CGRect imageRect = CGRectMake( xLocation, (16*(i % 30)), 16, 16);发布于 2011-04-13 11:11:06
在NSLog中将xLocation转换为int肯定是可行的,但也可以使用:
NSLog(@"imageRect %@", NSStringFromCGRect(imageRect));有一系列NSStringFromXXX帮助器函数不时会派上用场。
发布于 2011-04-13 09:13:40
%d未正确显示浮点数。使用%f或将xLocation转换为整数:
NSLog(@"%d", (int)xLocation);还可以通过每次计算来简化xLocation计算的可读性,如下所示
16 * (i / 30)在现代处理器上,开销是最小的。
https://stackoverflow.com/questions/5643339
复制相似问题