ios 将 UIButton 中的图像缩放到 AspectFit?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2025319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:45:29  来源:igfitidea点击:

scale Image in an UIButton to AspectFit?

iosobjective-ccocoa-touchuibuttonuikit

提问by KONG

I want to add an image to a UIButton, and also want to scale my image to fit with the UIButton (make image smaller). Please show me how to do it.

我想将图像添加到 UIButton,并且还想缩放我的图像以适应 UIButton(使图像更小)。请告诉我怎么做。

This is what I have tried, but it does't work:

这是我尝试过的,但不起作用:

  • Adding image to button and using setContentMode:
  • 将图像添加到按钮并使用setContentMode
[self.itemImageButton setImage:stretchImage forState:UIControlStateNormal];
[self.itemImageButton setContentMode:UIViewContentModeScaleAspectFit];
  • Making a "stretch image":
  • 制作“拉伸图像”:
UIImage *stretchImage = [updatedItem.thumbnail stretchableImageWithLeftCapWidth:0 topCapHeight:0];

采纳答案by gcamp

If you really want to scale an image, do it, but you should resize it before using it. Resizing it at run time will just lose CPU cycles.

如果您真的想缩放图像,请执行此操作,但您应该在使用前调整其大小。在运行时调整它的大小只会丢失 CPU 周期。

This is the category I'm using to scale an image :

这是我用来缩放图像的类别:

UIImage+Extra.h

UIImage+Extra.h

@interface UIImage (Extras)
- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize;
@end;

UIImage+Extra.m

UIImage+Extra.m

@implementation UIImage (Extras)

- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {

UIImage *sourceImage = self;
UIImage *newImage = nil;

CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;

CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;

CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;

CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

if (!CGSizeEqualToSize(imageSize, targetSize)) {

        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;

        if (widthFactor < heightFactor) 
                scaleFactor = widthFactor;
        else
                scaleFactor = heightFactor;

        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;

        // center the image

        if (widthFactor < heightFactor) {
                thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 
        } else if (widthFactor > heightFactor) {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
}


// this is actually the interesting part:

UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0);

CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width  = scaledWidth;
thumbnailRect.size.height = scaledHeight;

[sourceImage drawInRect:thumbnailRect];

newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

if(newImage == nil) NSLog(@"could not scale image");


return newImage ;
}

@end

You can use it to the size you want. Like :

您可以根据需要使用它。喜欢 :

[self.itemImageButton setImage:[stretchImage imageByScalingProportionallyToSize:CGSizeMake(20,20)]];

回答by Dave

I had the same problem. Just set the ContentMode of the ImageView that is inside the UIButton.

我有同样的问题。只需设置 UIButton 内 ImageView 的 ContentMode。

[[self.itemImageButton imageView] setContentMode: UIViewContentModeScaleAspectFit];
[self.itemImageButton setImage:[UIImage imageNamed:stretchImage] forState:UIControlStateNormal];

Hope this helps.

希望这可以帮助。

回答by nalexn

None of the answers here really worked for me, I solved the problem with the following code:

这里的答案都没有真正对我有用,我用以下代码解决了这个问题:

button.contentMode = UIViewContentModeScaleToFill;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;

You can do this in the Interface Builder as well.

您也可以在 Interface Builder 中执行此操作。

enter image description here

在此处输入图片说明

回答by Tanguy G.

The easiest way to programmatically set a UIButton imageView in aspect fitmode :

方面适合模式下以编程方式设置 UIButton imageView 的最简单方法:

Swift

迅速

button.contentHorizontalAlignment = .fill
button.contentVerticalAlignment = .fill
button.imageView?.contentMode = .scaleAspectFit

Objective-C

目标-C

button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
button.imageView.contentMode = UIViewContentModeScaleAspectFit;


Note: You can change .scaleAspectFit (UIViewContentModeScaleAspectFit) to .scaleAspectFill (UIViewContentModeScaleAspectFill) to set an aspect fillmode

注意:您可以将 .scaleAspectFit (UIViewContentModeScaleAspectFit) 更改为 .scaleAspectFill (UIViewContentModeScaleAspectFill) 以设置纵横比填充模式

回答by ninjaneer

I had problems with the image not resizing proportionately so the way I fixed it was using edge insets.

我遇到了图像没有按比例调整大小的问题,所以我修复它的方式是使用边缘插入。

fooButton.contentEdgeInsets = UIEdgeInsetsMake(10, 15, 10, 15);

回答by capikaw

This can now be done through IB's UIButton properties. The key is to set your image as a the background, otherwise it won't work.

这现在可以通过 IB 的 UIButton 属性来完成。关键是将您的图像设置为背景,否则将无法正常工作。

enter image description here

在此处输入图片说明

回答by Ortwin Gentz

Expanding on Dave's answer, you can set the contentModeof the button's imageViewall in IB, without any code, using Runtime Attributes:

扩展 Dave 的答案,您可以使用运行时属性在 IB 中设置contentMode按钮的imageView全部,无需任何代码:

enter image description here

在此处输入图片说明

  • 1means UIViewContentModeScaleAspectFit,
  • 2would mean UIViewContentModeScaleAspectFill.
  • 1意味着UIViewContentModeScaleAspectFit
  • 2将意味着 UIViewContentModeScaleAspectFill

回答by Tulleb

If you simply want to reduce your button image:

如果您只是想缩小按钮图像:

yourButton.contentMode = UIViewContentModeScaleAspectFit;
yourButton.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);

回答by Hamid Reza Ansari

1 - clear Button default text (important)

1 - 清除按钮默认文本(重要)

2 - set alignment like image

2 - 像图像一样设置对齐方式

3 - set content mode like image

3 - 设置内容模式,如图像

enter image description here

在此处输入图片说明

回答by Abedalkareem Omreyh

I have a method that does it for me. The method takes UIButtonand makes the image aspect fit.

我有一个方法可以为我做这件事。该方法采用UIButton并使图像方面适合。

-(void)makeImageAspectFitForButton:(UIButton*)button{
    button.imageView.contentMode=UIViewContentModeScaleAspectFit;
    button.contentHorizontalAlignment=UIControlContentHorizontalAlignmentFill;
    button.contentVerticalAlignment=UIControlContentVerticalAlignmentFill;
}