如何在 UIButton 中不拉伸图像

How to not stretch an image in UIButton(如何在 UIButton 中不拉伸图像)

本文介绍了如何在 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 但这似乎并没有改变任何东西.事实上,不同的 contentMode 似乎都没有改变任何东西.

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 吗?

Have you tried setImage instead of setBackgroundImage?

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

本文标题为:如何在 UIButton 中不拉伸图像