2012-01-08 119 views
0

我正在解析來自博客的RSS源,並將帖子的HTML放入UIWebView從HTML中獲取圖片大小

但現在我想改變圖像的大小,以適應iPhone屏幕。我試圖用下面的替換

HTMLContent = [HTMLContent stringByReplacingOccurrencesOfString:@"width=\"480\"" withString:@"width=\"300\""]; 

但是這樣做我只更換480寬度的圖像。而且我不會改變身高!

你知道是否有辦法用300代替任何寬度,並用相同的因子改變高度?

回答

3

您可以使用正則表達式來做到這一點。您需要匹配字符串中的<img>標籤,並提取高度和寬度值,然後計算新的所需高度和寬度,然後用新值替換字符串中的高度和寬度。

以下代碼應該可以工作,但它可能會遺漏一些邊緣情況(例如,如果height屬性出現在img標記的width屬性之前)。

int maxWidth = 300; 
NSString *originalHTML = @"<html><body><img src='image1.gif' width='4800' height='80' alt='foobar'/><img src='image1.gif' width='70000' height='99999' alt='foobar'/></body></html>"; 

NSString *regexPattern = @"<img[^>]*width=['\"\\s]*([0-9]+)[^>]*height=['\"\\s]*([0-9]+)[^>]*>"; 

NSRegularExpression *regex = 
[NSRegularExpression regularExpressionWithPattern:regexPattern 
              options:NSRegularExpressionDotMatchesLineSeparators 
              error:nil]; 

NSMutableString *modifiedHTML = [NSMutableString stringWithString:originalHTML]; 

NSArray *matchesArray = [regex matchesInString:modifiedHTML 
            options:NSRegularExpressionCaseInsensitive 
            range:NSMakeRange(0, [modifiedHTML length]) ]; 

NSTextCheckingResult *match; 

// need to calculate offset because range position of matches 
// within the HTML string will change after we modify the string 
int offset = 0, newoffset = 0; 

for (match in matchesArray) { 

    NSRange widthRange = [match rangeAtIndex:1]; 
    NSRange heightRange = [match rangeAtIndex:2]; 

    widthRange.location += offset; 
    heightRange.location += offset; 

    NSString *widthStr = [modifiedHTML substringWithRange:widthRange]; 
    NSString *heightStr = [modifiedHTML substringWithRange:heightRange]; 

    int width = [widthStr intValue]; 
    int height = [heightStr intValue]; 

    if (width > maxWidth) { 
     height = (height * maxWidth)/width; 
     width = maxWidth; 

     NSString *newWidthStr = [NSString stringWithFormat:@"%d", width]; 
     NSString *newHeightStr = [NSString stringWithFormat:@"%d", height]; 

     [modifiedHTML replaceCharactersInRange:widthRange withString:newWidthStr]; 

     newoffset = ([newWidthStr length] - [widthStr length]); 
     heightRange.location += newoffset; 

     [modifiedHTML replaceCharactersInRange:heightRange withString:newHeightStr];     

     newoffset += ([newHeightStr length] - [heightStr length]);    
     offset += newoffset; 
    } 
} 

NSLog(@"%@",modifiedHTML);