为UIButton拉伸背景图像

我得到的纹理比我的UIButton更短。

我得到了这个纹理:

在这里输入图像说明

我应该创build这个button:

在这里输入图像说明

我应该如何伸展(不瓷砖),这种纹理? 在水平方向上拉伸

日Thnx

从你提供的示例图像我很确定你正在寻找UIImageresizableImageWithCapInsets:

 UIImage *originalImage = [UIImage imageNamed:@"myImage.png"]; UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right); UIImage *stretchableImage = [originalImage resizableImageWithCapInsets:insets]; [myButton setBackgroundImage:stretchableImage forState:UIControlStateNormal]; // the image will be stretched to fill the button, if you resize it. 

UIEdgeInsets结构中的值决定了您不希望延伸的边距。 你的左右值可以是这么宽:

在这里输入图像说明

顶部和底部的值可以是0(如果你不想垂直调整button大小),或者可能是总高度的一半。

使用Xcode 6(和iOS7 +目标)时,可以在处理图像资源时使用切片编辑器。 使用编辑器切换切片模式– >显示切片菜单,或者在使用编辑器select特定图像时按下显示切片button(如下所示)。

显示切片按钮

然后,您可以select特定显示比例的图像并拖动规则或手动编辑插入值。

规则

之后,你可以在界面生成器中UIButton 背景图片select这个图片 (IBbutton的表示可能看起来很糟糕,但运行时应该是正确的)。

我的button看起来不错(运行iOS 7.1模拟器和iOS 8设备)。

在这里输入图像说明

这个苹果文档链接可能会有所帮助。

通过不平铺,我假设你可以不使用

 - (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets 

做你想做的事情的方法是使用:

 UIGraphicsBeginImageContextWithOptions(newSize, NO, 0); // should be proportionally larger CGContextRef context = UIGraphicsGetCurrentContext(); CGContextDrawImage(context, (CGRect){{0,0}, newSize}, [yourImage CGImage]); UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; 

使用stretchableImageWithLeftCapWidth:topCapHeight:方法。

请参阅: https : //github.com/boctor/idev-recipes/tree/master/StretchableImages

或使用可伸缩图像

 UIImage* imgbkg =[[UIImage imageNamed: @"my_bkg_image.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:10]; [_button setBackgroundImage: imgbkg forState: UIControlStateNormal]; 

如果你不想拉伸某一边,使用0