【发布时间】:2012-09-19 09:23:29
【问题描述】:
我得到了比我的 UIButton 更短的纹理。
我得到了这个纹理:
我应该创建这个按钮:
我应该如何拉伸(不是平铺)这种纹理?横向拉伸
谢谢
【问题讨论】:
标签: ios uibutton uiimage textures
我得到了比我的 UIButton 更短的纹理。
我得到了这个纹理:
我应该创建这个按钮:
我应该如何拉伸(不是平铺)这种纹理?横向拉伸
谢谢
【问题讨论】:
标签: ios uibutton uiimage textures
根据您提供的示例图片,我很确定您正在寻找 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(如果您不想垂直调整按钮的大小),也可以是总高度的一半。
【讨论】:
setBackgroundImage:forState 而不是setImage:forState。
借助 Xcode 6(和 iOS7+ 目标),您可以在处理图像资源时使用切片编辑器。 使用 Editor -> Show Slicing 菜单切换切片模式或在使用编辑器选择特定图像时按 Show Slicing 按钮(如下所示)。
然后您可以选择特定显示比例的图像并拖动规则或手动编辑插入值。
之后,您可以在 Interface Builder 中为 UIButton Background Image 选择此图像(IB 按钮的表示可能看起来很糟糕,但应该是运行时OK)。
我的按钮看起来不错(运行 iOS 7.1 模拟器和 iOS 8 设备)。
此 Apple 文档 link 可能会有所帮助。
【讨论】:
如果不平铺,我假设你不能使用
- (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
【讨论】:
resizableImageWithCapInsets: 已弃用
或使用可拉伸图像:
UIImage* imgbkg =[[UIImage imageNamed: @"my_bkg_image.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:10];
[_button setBackgroundImage: imgbkg forState: UIControlStateNormal];
如果您不想拉伸某一侧,请使用 0。
【讨论】:
resizableImageWithCapInsets: 已弃用