我得到了比我的 UIButton 更短的纹理。
我得到了这个纹理:
我应该创建这个按钮:
我应该如何拉伸(而不是平铺)这种纹理?水平方向拉伸
谢谢
UIImage
从您提供的示例图像中,我很确定您正在寻找resizableImageWithCapInsets:
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(如果您不想垂直调整按钮的大小),或者可能是总高度的一半。
使用 Xcode 6(和iOS7+目标),您可以在处理图像资源时使用切片编辑器。使用编辑器切换切片模式-> 显示切片菜单或在使用编辑器选择特定图像时按显示切片按钮(如下所示)。
然后,您可以选择特定显示比例的图像并拖动规则或手动编辑插入值。
之后,您可以在Interface Builder中为UIButton 背景图像选择此图像(IB 按钮的表示可能看起来很糟糕,但在运行时应该没问题)。
我的按钮看起来不错(运行 iOS 7.1 模拟器和 iOS 8 设备)。
这个 Apple 文档链接可能会有所帮助。
通过不平铺,我假设您因此不能使用
- (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 。