如何防止按钮的背景图像拉伸? [英] How do I prevent a button's background image from stretching?

查看:112
本文介绍了如何防止按钮的背景图像拉伸?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将UIButtonTypeCustom UIButton分配给UIView,其背景图片小于按钮的框架。图像更小的原因是因为我想为UIButton添加更多的目标区域。

I'm allocating a UIButtonTypeCustom UIButton to a UIView with a background image that is smaller than the button's frame. Reason why the image is smaller is because I'm trying to add more of a "target area" for the UIButton. However, the image is being scaled to the full size of the frame, rather than just being the image's size.

我已经尝试将UIButton和UIButton的imageView contentMode属性设置为true,然后将图片缩放到整个框架的大小,而不是图片的大小。 UIViewContentModeScaleAspectFit,但没有运气,图像仍然被拉伸。

I have tried setting the UIButton and UIButton's imageView contentMode property to "UIViewContentModeScaleAspectFit", but no luck, the image still gets stretched out.

有没有办法做我想以编程方式做?

Is there a way to do what I'm trying to do programmatically?

提前感谢!

推荐答案

很多人犯了同样的错误关于按钮图像,然后跳过箍,试图使按钮按照他们期望的行为。让我们一次性清楚一下:

A lot of people make the same mistake you do in regards to button images and then jump through hoops trying to make the button behave as they expect it to. Let's clear this up once and for all:

A UIButton 有两种类型的图片可以显示 - 前景图像和背景图片。按钮的背景图像应该替换按钮的背景纹理。因此,它延伸以填充整个背景是有意义的。但是,按钮的前景图像应该是可以或可以不与文本一起显示的图标;它不会伸展。如果框架小于图片,它可能会缩小,但它不会拉伸。您甚至可以使用Interface Builder中的控件对齐属性设置前景图像的对齐方式。

A UIButton has two types of images it can display -- a foreground image and a background image. The background image for a button is expected to replace the button's background texture. As such, it makes sense that it stretches to fill the entire background. However, the button's foreground image is expected to be an icon that may or may not display alongside text; it will not stretch. It may shrink if the frame is smaller than the image, but it will not stretch. You can even set the alignment of the foreground image using the Control alignment properties in Interface Builder.

按钮的前景和背景图片可以用下面的代码设置:

A button's foreground and background image can be set in code like this:

// stretchy
[self setBackgroundImage:backgroundImage forState:UIControlStateNormal];  

// not stretchy
[self setImage:forgroundImage forState:UIControlStateNormal]; 

这篇关于如何防止按钮的背景图像拉伸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆