2015-12-29 33 views
2

需要你的幫助,我輸入CGSize(例如):200x300。並與其他陣列CGSize's = [20x20, 100x100, 150x150, 200x100, 200x250, 300x300...]。 請幫我在陣列已經比較最好的百分比(例如其200x250)...比較兩個CGSize的最佳persentage

我試圖使用枚舉,例如尋找最好的項目:

CGSize inputSize = CGSizeMake(200, 300); 
for (int i = 0; i < array.count; i++) 
{ 
    CGSize concurentSize = CGSizeZero; 
    switch (i) 
    { 
    case 0: 
    { 
     concurentSize.width = 20; 
     concurentSize.height = 20; 
    } 
    and so on... 

    float differencePercentWidth = (concurentSize.width/inputSize.width) * 100.0; 
    float differencePercentHeight = (concurentSize.height/inputSize.height) * 100.0; 

    if (differencePercentWidth > 90 && differencePercentHeight > 90) 
    { 
     // FOUND best CGSize... stop 
     break. 
    } 
} 

但是,它不工作,它differencePercentWidth/differencePercentHeight可以> 100 =(

我需要一些方法或函數,可以比較2點CGSize的百分比匹配...。例如:尺寸200x300是具有大小200x250 ...東西最佳匹配如:

float matchesInPerсent = CGSizeCompare(firstCGSize, secondCGSize); 
//matchesInPerсent = 0.6; // in percents 

請幫忙,對不起,我的英文,如果你需要更多的細節,請讓我知道。謝謝。

+0

基於總像素或每個寬度和高度的最佳比較百分比? – Jay

+0

寬度和高度差的平方和的平方根可能會給你準確的結果。您選擇最小值的尺寸。 – Cristik

+0

只是爲了讓它適合200x300,更適合的尺寸是400x600或200x301? – 4oby

回答

1

嘗試類似的邏輯來計算數組中的最大數量,但需要小於一個有限值。在這種情況下,計算最大百分比平均值size.widthsize.height,最高百分比接近1即爲贏家。如果您還需要100%的上限值,那麼您需要插入邏輯以使該值低於100%,並在這些大小上運行相同的邏輯。

這裏是代碼,它會給你距離數組最近的百分比大小。

/* 

sizes : array of the sizes represented in NSValue format 
size: The size for which you need closest value. 

*/ 
- (CGSize)bestMatch:(NSArray *)sizes withSize:(CGSize)size { 
     float bestMatch = 0.0; 
     CGSize bestMatchSize = CGSizeZero; 
     for (NSValue *value in sizes) { 
      float percentage = (value.CGSizeValue.width/size.width + value.CGSizeValue.height/size.height)/2; 

      //If you need greater then 100% and closes to the size 
      if (percentage > 1.0) { 
       percentage = -1*(percentage - 2); 
      } 

      if (bestMatch < percentage && percentage < 1) { 
       bestMatch = percentage; 
       bestMatchSize = value.CGSizeValue; 
      } 
     } 
     //If you need best match you can return bestMatch which is closest in percentage 

     return bestMatchSize; 

}