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

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

提前致谢。

4

5 回答 5

19

实现此目的的一种方法是使用以下方法,

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

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

[imgView setImage: backgroundImg];

UIEdgeInsetsMake(2,2, 2, 2) 是您希望不可拉伸的像素数量。

于 2012-10-11T14:53:04.803 回答
4

Tortuga22软件可以实现九个补丁

你可以在这里找到这个 GitHub 的源代码

像这样使用它

[btnSubmit setImage: [TUNinePatchCache imageOfSize:[btnSubmit bounds].size 
                                forNinePatchNamed:@"imgNormalBackground"]
                       forControlState:UIControlStateNormal];
于 2012-12-26T14:35:05.443 回答
2

从 iOS5 开始,您可以使用resizableImageWithCapInsets:来实现这一点。

于 2011-11-28T07:02:40.557 回答
1

I didn't want to load so much code for the simple 9 patch images we had. So anyway, here's a simple solution to the problem for those interested. It's somewhat hard coded to our 3 pixel stretch regions but you could easily adjust those to your needs or find those in the image with some basic code and use that instead of my hard-coded inset parameters.

+ (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;

}

Then to use it in say, a button's background, just call it like this:

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

Done.

于 2013-09-09T23:17:10.490 回答
0

如果我理解正确,您希望矩形的长度和高度增加。虽然可能有更有效的解决方案,但我可以建议将边界分解为一个基本单元。一个接一个地重复添加此图像,以形成所需长度和高度的边框矩形。然后用灰色绘制内部矩形。

于 2011-10-27T15:00:55.833 回答