拉伸像android九补丁的图像?

时间:2011-10-25 07:45:53

标签: ios objective-c iphone ipad nine-patch

UIImage方法:

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

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

我无法设置可伸缩区域,所以我想知道:是否有UIImage类别可以做到这一点?

我用Google搜索后,发现了一个lib。

问题: Is there a nine-patch loader for iPhone?

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

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

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

提前致谢。

5 个答案:

答案 0 :(得分:19)

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

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

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

[imgView setImage: backgroundImg];

UIEdgeInsetsMake(2,2,2,2)是您想要不可伸展的像素数量。

答案 1 :(得分:4)

您可以使用Tortuga22 software

实现九个补丁

您可以从此GitHub here

中找到来源

像这样使用

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

答案 2 :(得分:2)

从iOS5开始,您可以使用resizableImageWithCapInsets:来实现此目的。

答案 3 :(得分:1)

我不想为我们拥有的简单9补丁图片加载这么多代码。所以无论如何,对于那些感兴趣的人来说,这是一个简单的问题解决方案。它有点硬编码到我们的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];

完成。

答案 4 :(得分:0)

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