2319

# 当需要保留图片中间、拉伸两端时

## 原理：

``````1、计算图片大小与目标大小差距，获得需拉伸的宽度；\
2、计算拉伸左边区域的 `UIEdgeInsets`，第一次拉伸后的图片宽度 ` tempStrecthWith`;\
3、生成拉伸左侧部分的图片;\
4、计算拉伸右侧区域的 `UIEdgeInsets` 及拉伸后的图片宽度;\
5、生成拉伸右侧部分的图片，结束;\
``````

## 代码

``````/**
拉伸两端，保留中间

@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)];
}
``````