iOS 圖片拉伸、拉伸兩端保留中間

時光易逝發表於2018-11-19

當需要保留圖片中間、拉伸兩端時

原理:

1、計算圖片大小與目標大小差距,獲得需拉伸的寬度;\
2、計算拉伸左邊區域的 `UIEdgeInsets`,第一次拉伸後的圖片寬度 ` tempStrecthWith`;\
3、生成拉伸左側部分的圖片;\
4、計算拉伸右側區域的 `UIEdgeInsets` 及拉伸後的圖片寬度;\
5、生成拉伸右側部分的圖片,結束;\
複製程式碼

注意:desSize目標大小,最好傳入整數

程式碼

/**
 拉伸兩端,保留中間
 
 @param image 需要拉伸的圖片
 @param desSize 目標大小
 @param stretchLeftBorder 拉伸圖片距離左邊的距離
 @param top inset.top
 @param bottom inset.bottom
 @return 拉伸收縮後的圖片
 */
static UIImage *tt_stretch_both_sides_image(UIImage *image, CGSize desSize, CGFloat stretchLeftBorder, CGFloat top, CGFloat bottom) {
    if (!image) {
        return nil;
    }
    if (desSize.width == 0) {
        return nil;
    }
    CGSize imageSize = image.size;
    
    if (fabs(desSize.width - imageSize.width) <= 4) {
        return image;
    }
    
    imageSize.width = floor(imageSize.width);
    desSize.width   = floor(desSize.width);
    
    BOOL desSizeThan = desSize.width > imageSize.width;
    
    //各需要拉伸的寬度
    CGFloat needWidth = 0;
    needWidth = (desSize.width - imageSize.width) /2.0;
    
    //先拉取左邊
    CGFloat left = stretchLeftBorder;
    CGFloat right = desSizeThan? (imageSize.width - left -1): (imageSize.width - fabs(needWidth) -left);
    
    
    //畫圖, 生成拉伸的左邊後的圖片
    CGFloat tempStrecthWith = 0;
    tempStrecthWith = imageSize.width + needWidth;
    
    //生成拉伸後的圖片-》左
    CGFloat height = imageSize.height;
    UIImage *strectedImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(0, left, 0, right)];
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(tempStrecthWith, height), NO, image.scale);
    [strectedImage drawInRect:CGRectMake(0, 0, tempStrecthWith, height)];
    strectedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //拉伸右邊
    right = stretchLeftBorder;
    left  = desSizeThan? (strectedImage.size.width - right - 1): (strectedImage.size.width - right - fabs(needWidth));
    
    //生成拉伸後的圖片-》右
    tempStrecthWith = desSize.width;
    strectedImage = [strectedImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, left, 0, right)];
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(tempStrecthWith, height), NO, image.scale);
    [strectedImage drawInRect:CGRectMake(0, 0, tempStrecthWith, height)];
    strectedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return [strectedImage resizableImageWithCapInsets:UIEdgeInsetsMake(top, 0, bottom, 0)];
}
複製程式碼

相關文章