ios 拉伸背景图中间图片不变四周拉伸

上图中间区域的翅膀不能变形,Android的点九能很好的解决,但是iOS的stretchableImageWithLeftCapWidth没法一次性指定拉伸区域,最后发现https://www.jianshu.com/p/bb3300cf15c4 的解决思路,然后修改了下,/**
 拉伸图片 -- 拉伸四周保持中间大图不变形

 @param size 所需要设置的大小
 @param baseImage 原图
 @return 拉伸好的图片
 */
- (UIImage *)dc_stretchLeftAndRightWithContainerSize:(CGSize)size baseImage:(UIImage *)baseImage
{
    // 248 中间图片的宽  273 中间图片的高
    CGFloat top = (baseImage.size.height - 248)/2;
    CGFloat left = (baseImage.size.width - 273)/2;
    CGSize imageSize = baseImage.size;
    CGSize bgSize = size;
    
    //1.第一次拉伸下面 保护上面
   
    UIImage *image = [baseImage stretchableImageWithLeftCapWidth:left+273 topCapHeight:top+248];
    
    //第一次拉伸的距离之后图片总宽度
    CGFloat tempWidth = (bgSize.width)/2 + imageSize.width/2;
    CGFloat tempHeight = (bgSize.height)/2 + imageSize.height/2;
    
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(image.size.width, tempHeight), NO, [UIScreen mainScreen].scale);
    
    [image drawInRect:CGRectMake(0, 0, tempWidth, tempHeight)];
    
    //拿到拉伸过的图片
    UIImage *firstStrechImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //2.第二次拉伸上面 保护下面
    
    UIImage *secondStrechImage = [firstStrechImage stretchableImageWithLeftCapWidth:left topCapHeight:top];
    
    return secondStrechImage;
}

可以有效解决

猜你喜欢

转载自www.cnblogs.com/pp-pping/p/10345252.html