如何不在UIButton中拉伸图像 [英] How to not stretch an image in UIButton

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

问题描述

我试图以编程方式创建一个自定义UITableViewCell,这个单元格的一个子视图将是一个带有图像的按钮(放大镜的简单图像)。但是,我想让按钮的图像居中,按比例缩小以适应按钮,而不是拉伸填充整个按钮。下面是我的代码,其中self指的是放置按钮的自定义UITableViewCell。

I'm trying to create a custom UITableViewCell programmatically and one of the subviews of this cell is going to be a button with an image in it (a simple image of a magnifying glass). However, I want the button's image to be centered and scaled proportionately down to fit in the button and NOT to be stretched to fill the entire button. Below is my code where self refers to the custom UITableViewCell which I am placing the button into.

self.myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[self.myButton setBackgroundImage:[UIImage imageNamed: @image_name_here"] forState:UIControlStateNormal];
self.myButton.frame = CGRectMake(...//something, something)
self.myButton.imageView.contentMode = UIViewContentModeCenter;
[self.contentView addSubview:self.mySearchHelpButton];

现在图像拉伸填充整个按钮,而不是按比例缩放,以便它很好地适合。

Right now the image stretches to fill the entire button rather than scaling proportionately so that it fits nicely.

我也尝试将contentMode设置为 UIViewContentModeScaleAspectFill 但这似乎没有改变任何东西。事实上,没有一个不同的contentModes似乎改变任何东西。

I have also tried setting the contentMode to UIViewContentModeScaleAspectFill but this doesn't seem to change anything. In fact, none of the different contentModes seem to change anything.

推荐答案

您尝试过 setImage 而不是 setBackgroundImage

这篇关于如何不在UIButton中拉伸图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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