如何在不拉伸中心的情况下拉伸UIImageView?

nju*_*xjy 13 iphone ios

在此输入图像描述

我想拉伸上面所示图片的左右两侧,并保持中间箭头不拉伸.我怎样才能做到这一点?

Ale*_*lds 7

使用Photoshop或其他图像编辑工具将图像分成两部分:边缘和中心.边缘图像可以是一个像素宽并用于左右边缘; 然而,中心有很多像素宽,可以捕捉到箭头.然后,您可以将三个UIImageView实例彼此相邻:左边缘,中心边缘和右边缘.左右边缘调整为所需宽度,而中心保持其原始尺寸.


Kla*_*aas 7

如果你不喜欢打扰Photoshop,并且如果图像没有通过动态调整大小,你可以在UIImage上使用我的类别方法.

名为"17maA.png"的示例图像宽度为124像素.因此,您可以轻松地创建一个300像素宽的版本:

UIImage *image = [UIImage imageNamed:@"17maA"];
UIImage *newImage = [image pbResizedImageWithWidth:300 andTiledAreaFrom:10 to:20 andFrom:124-20 to:124-10];
Run Code Online (Sandbox Code Playgroud)

这是类别方法:

- (UIImage *)pbResizedImageWithWidth:(CGFloat)newWidth andTiledAreaFrom:(CGFloat)from1 to:(CGFloat)to1 andFrom:(CGFloat)from2 to:(CGFloat)to2  {
    NSAssert(self.size.width < newWidth, @"Cannot scale NewWidth %f > self.size.width %f", newWidth, self.size.width);

    CGFloat originalWidth = self.size.width;
    CGFloat tiledAreaWidth = (newWidth - originalWidth)/2;

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(originalWidth + tiledAreaWidth, self.size.height), NO, self.scale);

    UIImage *firstResizable = [self resizableImageWithCapInsets:UIEdgeInsetsMake(0, from1, 0, originalWidth - to1) resizingMode:UIImageResizingModeTile];
    [firstResizable drawInRect:CGRectMake(0, 0, originalWidth + tiledAreaWidth, self.size.height)];

    UIImage *leftPart = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(newWidth, self.size.height), NO, self.scale);

    UIImage *secondResizable = [leftPart resizableImageWithCapInsets:UIEdgeInsetsMake(0, from2 + tiledAreaWidth, 0, originalWidth - to2) resizingMode:UIImageResizingModeTile];
    [secondResizable drawInRect:CGRectMake(0, 0, newWidth, self.size.height)];

    UIImage *fullImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return fullImage;
}
Run Code Online (Sandbox Code Playgroud)