像Android的九宫格一样拉伸图片吗?

12

UIImage 方法:

- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight

这里可拉伸的区域被强制为一个像素高/宽。

我不能设置可拉伸的区域,所以想知道:是否有一种 UIImage 类别可以实现这个功能?

经过谷歌搜索,我找到了一个库。

问题:是否有适用于 iPhone 的九宫格加载器?

公告:http://blog.tortuga22.com/2010/05/31/announcing-tortuga-22-ninepatch/

http://i.stack.imgur.com/Rc6my.png

这是一个源图片,我想拉伸内部的灰色矩形。

提前致谢!


为什么你不使用适用于iPhone的九宫格加载器? - Manali
可能会有更好的解决方案,比如一个UIImage分类或类似的东西:
  • (UIImage *)imageWithStretchableRect:(CGRect)rect destRect:(CGRect)destRect
- guoxj
我使用了这个库,但效果不是我想要的。我想要重复图像的某些部分。 - guoxj
5个回答

20

实现这个目的的一种方法是使用下面的方法:

UIImage * backgroundImg = [UIImage imageNamed:@"bg.png"];

backgroundImg = [backgroundImg resizableImageWithCapInsets:UIEdgeInsetsMake(2,2, 2, 2)];

[imgView setImage: backgroundImg];

UIEdgeInsetsMake(2,2, 2, 2) 表示你想要不被拉伸的像素数量。


4

你可以使用 Tortuga22 软件 实现九宫格效果。

你可以在这个 GitHub 链接 找到源代码。

使用方法如下:

[btnSubmit setImage: [TUNinePatchCache imageOfSize:[btnSubmit bounds].size 
                                forNinePatchNamed:@"imgNormalBackground"]
                       forControlState:UIControlStateNormal];

2
从iOS5开始,您可以使用resizableImageWithCapInsets:来实现此功能。

1
我不想为我们拥有的简单九宫格图像加载太多代码。因此,对于那些感兴趣的人,这里有一个简单的解决方案。它在一定程度上是针对我们的3像素拉伸区域进行硬编码的,但您可以轻松地根据自己的需求调整它们,或者使用一些基本的代码找到图像中的拉伸区域并代替我的硬编码插入参数。
+ (UIImage *) makeNinePatchImage:(UIImage *)image;
{
    //Clear the black 9patch regions
    CGRect imageRect = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
    UIGraphicsBeginImageContextWithOptions(image.size, NO, [UIScreen mainScreen].scale);
    [image drawInRect:imageRect];

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextClearRect(context, CGRectMake(0, 0, image.size.width, 1));
    CGContextClearRect(context, CGRectMake(0, 0, 1, image.size.height));

    image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    UIEdgeInsets insets;

    //hard coded for now, could easily read the black regions if necessary
    insets.left = insets.right = image.size.width / 2 - 1;
    insets.top = insets.bottom = image.size.height / 2 - 1;

    UIImage *nineImage = [image resizableImageWithCapInsets:insets     
                          resizingMode:UIImageResizingModeStretch];

    return nineImage;

}

然后,如果要将它用于按钮的背景中,只需像这样调用:

[self.dummyButton setBackgroundImage:[EVUtility makeNinePatchImage:learnMoreImage] forState:UIControlStateNormal];

完成。


0

如果我理解正确,您想让矩形的长度和高度增加。 虽然可能有更有效的解决方案,但我可以建议的是将边界分成基本单位。将此图像重复放在一起,形成所需长度和高度的边框矩形。然后用灰色涂内部矩形。


是的,没错。我只想重复图像的一部分。谢谢你的回答,确实帮了我。 - guoxj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接