我想在我的IOS应用中使用9补丁图片。有可能吗?
答案 0 :(得分:18)
查看UIImage的方法resizableImageWithCapInsets:(UIEdgeInsets)capInsets
。
答案 1 :(得分:2)
您可以尝试这个简单的实现: https://github.com/shiami/SWNinePatchImageFactory
这个概念很简单,如下所述:
该技术仅用于将9补丁PNG图像转换为iOS兼容,可调整大小的UIImage对象。 有关详细信息,请参阅UIImage的方法resizableImageWithCapInsets:(UIEdgeInsets)insets。 所以它只支持在水平和垂直两侧拉伸一段补丁标记。
+ (UIImage*)createResizableImageFromNinePatchImage:(UIImage*)ninePatchImage
{
NSArray* rgbaImage = [self getRGBAsFromImage:ninePatchImage atX:0 andY:0 count:ninePatchImage.size.width * ninePatchImage.size.height];
NSArray* topBarRgba = [rgbaImage subarrayWithRange:NSMakeRange(1, ninePatchImage.size.width - 2)];
NSMutableArray* leftBarRgba = [NSMutableArray arrayWithCapacity:0];
int count = [rgbaImage count];
for (int i = 0; i < count; i += ninePatchImage.size.width) {
[leftBarRgba addObject:rgbaImage[i]];
}
int top = -1, left = -1, bottom = -1, right = -1;
count = [topBarRgba count];
for (int i = 0; i <= count - 1; i++) {
NSArray* aColor = topBarRgba[i];
if ([aColor[3] floatValue] == 1) {
left = i;
break;
}
}
NSAssert(left != -1, @"The 9-patch PNG format is not correct.");
for (int i = count - 1; i >= 0; i--) {
NSArray* aColor = topBarRgba[i];
if ([aColor[3] floatValue] == 1) {
right = i;
break;
}
}
NSAssert(right != -1, @"The 9-patch PNG format is not correct.");
for (int i = left + 1; i <= right - 1; i++) {
NSArray* aColor = topBarRgba[i];
if ([aColor[3] floatValue] < 1) {
NSAssert(NO, @"The 9-patch PNG format is not support.");
}
}
count = [leftBarRgba count];
for (int i = 0; i <= count - 1; i++) {
NSArray* aColor = leftBarRgba[i];
if ([aColor[3] floatValue] == 1) {
top = i;
break;
}
}
NSAssert(top != -1, @"The 9-patch PNG format is not correct.");
for (int i = count - 1; i >= 0; i--) {
NSArray* aColor = leftBarRgba[i];
if ([aColor[3] floatValue] == 1) {
bottom = i;
break;
}
}
NSAssert(bottom != -1, @"The 9-patch PNG format is not correct.");
for (int i = top + 1; i <= bottom - 1; i++) {
NSArray* aColor = leftBarRgba[i];
if ([aColor[3] floatValue] == 0) {
NSAssert(NO, @"The 9-patch PNG format is not support.");
}
}
UIImage* cropImage = [ninePatchImage crop:CGRectMake(1, 1, ninePatchImage.size.width - 2, ninePatchImage.size.height - 2)];
return [cropImage resizableImageWithCapInsets:UIEdgeInsetsMake(top, left, bottom, right)];
}
SWNinePatchImageView还提供Nib或Storyboard用法。 您可以在仓库中检查示例项目。
答案 2 :(得分:0)
最可能的结果是 https://github.com/andylanddev/Tortuga22-NinePatch 9-patch库已经使用了波纹管方法 resizableImageWithCapInsets:(UIEdgeInsets)插图