mar*_*rty 100 iphone uibutton ios aspect-fit
我有几个UIButtons,在IB中它们被设置为Aspect Fit,但由于某种原因它们总是拉伸.还有别的东西要设置吗?我尝试了所有不同的视图模式,但没有一个工作,它们都伸展开来.
Wer*_*her 228
解决方案是设置contentModeon的imageView属性UIButton.在UIButton必须用自定义的类型来创建这个工作,我相信(否则nil返回该属性).
小智 50
这种方法对我很有用:
在Xib中选择按钮并设置user defined runtime attributes:
self.imageView.contentModeNumber1
我们使用数字因为你不能在那里使用枚举.但是UIViewContentModeScaleAspectFit等于1.
Dan*_*Ray 43
我以前遇到过这个问题.我通过投入我的形象解决了这个问题UIImageView,在这里contentMode设置的实际工作,并把一个透明的定制UIButton过的那顶.
编辑:这个答案已经过时了.请参阅@Werner Altewischer在iOS现代版中的正确答案的答案.
ave*_*dev 21
如果您在Interface Builder中执行此操作,则可以使用运行时属性检查器直接设置它而无需任何代码.
将按钮上的键路径设置为"imageView.contentMode",类型为"Number",值为"1"(或者您希望使用哪种模式).
Ahm*_*ker 12
使用button的imageView for contentMode.不是直接在按钮本身.
homeButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
homeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
homeButton.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
[homeButton setImage:[UIImage imageNamed:kPNGLogo] forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)
如果你把图像在UIImageView后面的按钮,你会松动的内置功能UIButton类,如adjustsImageWhenHighlighted和adjustsImageWhenDisabled,当然还有能力来设置不同的图像的不同状态(不这样做你自己的hazzle).
如果我们想要为所有控制状态取消图像,一个approuch是使用获取图像imageWithCGImage:scale:orientation,如下面的方法:
- (UIImage *) getScaledImage:(UIImage *)img insideButton:(UIButton *)btn {
// Check which dimension (width or height) to pay respect to and
// calculate the scale factor
CGFloat imgRatio = img.size.width / img.size.height,
btnRatio = btn.frame.size.width / btn.frame.size.height,
scaleFactor = (imgRatio > btnRatio
? img.size.width / btn.frame.size.width
: img.size.height / btn.frame.size.height;
// Create image using scale factor
UIImage *scaledImg = [UIImage imageWithCGImage:[img CGImage]
scale:scaleFactor
orientation:UIImageOrientationUp];
return scaledImg;
}
Run Code Online (Sandbox Code Playgroud)
为了实现这一点,我们写道:
UIImage *scaledImg = [self getScaledImage:myBtnImg insideButton:myBtn];
[myBtn setImage:scaledImg forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)
这应该可以防止图像在所有控制状态下伸展.它对我有用,但如果没有,请告诉我!
注意:在这里,我们正在解决与之相关的问题UIButton,但insideButton:也可能是insideView:,或者任何人想要适应图像的问题.
我曾经有过这个问题.我遇到的问题是我试图将此效果应用于有限的背景UIButton,因此意味着您无法轻松调整它.
诀窍是将其设置为图像然后应用@ ayreguitar的技术,这应该解决它!
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton setContentMode:UIViewContentModeScaleAspectFill];
[myButton setImage:@"myImage.png" forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)