我正在尝试为iOS中的布局问题找到合理的解决方案。
我需要在这个布局的视图中加载n个图像:
-----------
| x x |
| x x |
| x x |
| x x |
| x x |
| x x |
-----------
每个图像可能有不同的宽度,但高度最大,每个图像都在其列的中心。
建议的方法是什么?
我想将50%宽度的视图并排放置,然后将图像置于其中。
谢谢!
答案 0 :(得分:3)
这应该让你开始。但是,它没有考虑图像的比例。
CGRect bounds = [[UIScreen mainScreen] bounds];
CGFloat maxCol = [imageViewArray count] + ([imageViewArray count] % 2);
CGFloat width = (bounds.size.width/2) - 15;
CGFloat height = (bounds.size.height/maxCol) - 10;
// loop through imageViews
for(pos = 0; pos < [imageViewArray count]; pos++)
{
// calculate position within grid
CGFloat row = (pos/2);
CGFloat col = (pos%2);
// retrieves UIImageView and UIImage
imageView = [imageViewArray objectAtIndex:pos];
image = imageView.image;
// calculates image size
CGFloat scaledWidth = (height * image.size.width) / image.size.height;
// adjust size of image view
imageView.frame = CGRectMake(0, // temp value for x
0, // temp value for y
height, // width of image
scaledWidth); // height of image
// adjust position of image view
imageView.center = CGPointMake((bounds.size.width/3) + ((bounds.size.width/3) * col),
((height+10) * row) + (height+10)/2));
// add image view to super view
[rootView addSubView:imageView];
};
上述缩放假设网格位置的高度始终小于网格位置的宽度。
答案 1 :(得分:2)
如果要加载大量图像,则会导致性能问题。更好的方法 - 将UITableView
与custom cells一起使用。
答案 2 :(得分:1)
在渲染字形时看起来与文本引擎相同。您要做的是在执行任何其他操作之前首先计算行的宽度。这是通过从左到右循环完成的,添加视图的大小直到您到达边缘并且无法添加更多。然后,您知道该行的宽度和最大高度,并通过向左侧添加一个等于左侧边距除以2的边距来简单地居中。然后通过该行的最大高度为y坐标添加偏移量。
然后继续为所有观点继续这样做,直到他们都有位置。