iOS 图片拉伸、拉伸两端保留中间

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

原理:

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)];
}
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值