我不想为我们拥有的简单九宫格图像加载太多代码。因此,对于那些感兴趣的人,这里有一个简单的解决方案。它在一定程度上是针对我们的3像素拉伸区域进行硬编码的,但您可以轻松地根据自己的需求调整它们,或者使用一些基本的代码找到图像中的拉伸区域并代替我的硬编码插入参数。
+ (UIImage *) makeNinePatchImage:(UIImage *)image;
{
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;
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]
完成。