2012-03-05 98 views
1

我正在嘗試爲iOS中的佈局問題找到合理的解決方案。動態iOS佈局圖像

我需要在視圖中加載n個圖像與此佈局:

----------- 
| x x | 
| x x | 
| x x | 
| x x | 
| x x | 
| x x | 
----------- 

每個圖像可以具有不同的寬度,但高度具有最大和各圖像將被集中在它的列中。

建議的方法是什麼?

我正在考慮將50%寬度的視圖並排放置,然後將圖像居中。

謝謝!

+0

我不明白倒票。這個問題無效嗎? – 2012-03-06 00:49:45

回答

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]; 
}; 

上述縮放假定網格位置的高度總是大於網格位置的寬度小。

+0

謝謝,我試過你的代碼,是的,它似乎是正確的軌道上。 – 2012-03-06 00:19:12

1

看起來像文本引擎在渲染字形時遇到的問題。你想要做的是在你做任何事情之前先計算一行的寬度。這是通過從左到右循環完成的,添加視圖的大小,直到您到達邊緣並且無法添加更多。然後您就知道該行的寬度和最大高度,只需在左側添加偏移量即可將視圖居中,等於右側的餘量除以2。然後通過該行的最大高度向y座標添加一個偏移量。

然後簡單地繼續爲所有視圖做這件事,直到他們都有一個位置。

+0

要麼我不理解你的建議,要麼你不明白我的問題。我知道連續觀看次數(2)。所以在iphone中,每一列都會有160個寬度,我的問題是每個列中我需要居中圖像。 – 2012-03-06 00:25:38

2

如果您將加載大量圖像,將會導致性能問題。更好的方法 - 使用UITableViewcustom cells

+0

是的,它是一個選項,但是在綁定到每行的數據源上有兩個itens是不是很奇怪? – 2012-03-06 00:27:31

+0

不是什麼奇怪的事情?另外,如果我談論性能:你可以從'tableView:willDisplayCell:forRowAtIndexPath:'中的文件系統加載圖像。 – 2012-03-06 00:37:08

+0

我是iOS開發新手,我的理解是uitableview的概念是有一個數據源並將一個項目綁定到每一行。這就是爲什麼我說它把數據源中的兩個元素綁定到每一行感覺很奇怪。但如果它確定,那麼它絕對是一種選擇。謝謝 – 2012-03-06 00:48:28