简体   繁体   English

如何缩放 UIButton 的 imageView?

[英]How do I scale a UIButton's imageView?

I created a UIButton instance named "button" with an image using [UIButton setImage:forState:] .我使用[UIButton setImage:forState:]用图像创建了一个名为“button”的 UIButton 实例。 The button.frame is larger than the image's size. button.frame 大于图像的大小。

Now I want to scale this button's image smaller.现在我想缩小这个按钮的图像。 I tried changing button.imageView.frame , button.imageView.bounds and button.imageView.contentMode , but all seem ineffective.我尝试更改button.imageView.framebutton.imageView.boundsbutton.imageView.contentMode ,但似乎都无效。

Can anyone help me scale a UIButton 's imageView?谁能帮我缩放UIButton的 imageView?

I created the UIButton like this:我像这样创建了UIButton

UIButton *button = [[UIButton alloc] init];
[button setImage:image forState:UIControlStateNormal];

I tried to scale the image like this:我试图像这样缩放图像:

button.imageView.contentMode = UIViewContentModeScaleAspectFit;
button.imageView.bounds = CGRectMake(0, 0, 70, 70);

and this:和这个:

button.imageView.contentMode = UIViewContentModeScaleAspectFit;
button.imageView.frame = CGRectMake(0, 0, 70, 70);

For the original poster, here is the solution I found:对于原始海报,这是我找到的解决方案:

commentButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;

This will allow your button to scale horizontally.这将允许您的按钮水平缩放。 There is a vertical setting as well.还有一个垂直设置。

Took me several hours to figure that one out (the naming of the property is very unintuitive) so figured I'd share.我花了几个小时才弄明白(属性的命名非常不直观),所以我想分享一下。

I'd faced similar problem, where I've a background Image (one with border) and an image (flag) for a custom button.我遇到过类似的问题,我有一个背景图像(一个带边框的)和一个自定义按钮的图像(标志)。 I wanted flag to be scaled down and in center.我希望标志按比例缩小并居中。 I tried changing imageView's attribute but didn't succeed and was seeing this image --我尝试更改 imageView 的属性但没有成功并且看到了这张图片——

在此处输入图片说明

During my experiments, I tried :在我的实验中,我尝试了:

button.imageEdgeInsets = UIEdgeInsetsMake(kTop,kLeft,kBottom,kRight)

I achieved expected result as :我达到了预期的结果:

在此处输入图片说明

An Addition Way for config in XIB file. XIB 文件中配置的一种附加方式。 You can choose this option if you want text or image is Scale full fill in UIButton.如果您希望文本或图像在 UIButton 中按比例完全填充,则可以选择此选项。 It's will be the same with code.代码也是一样。

UIButton *btn = [UIButton new];

btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
btn.contentVerticalAlignment   = UIControlContentVerticalAlignmentFill;

在此处输入图片说明

use

button.contentMode = UIViewContentModeScaleToFill;

not不是

button.imageView.contentMode = UIViewContentModeScaleAspectFit;

Update:更新:

As @Chris commented,正如@Chris 评论的那样,

To get this to work for setImage:forState:, you need to do the following to scale horizontally: myButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;要使其适用于 setImage:forState:,您需要执行以下操作来水平缩放: myButton.contentHorizo​​ntalAlignment = UIControlContentHorizo​​ntalAlignmentFill;

    UIButton *button= [[UIButton alloc] initWithFrame:CGRectMake(0,0,70,70)];
    button.buttonType = UIButtonTypeCustom;
    UIImage *buttonImage = [UIImage imageNamed:@"image.png"];

    UIImage *stretchableButtonImage = [buttonImage stretchableImageWithLeftCapWidth:12 topCapHeight:0]; 
    [button setBackgroundImage:stretchableButtonImage forState:UIControlStateNormal]; 

I found this solution.我找到了这个解决方案。

1) Subclass the following methods of UIButton 1) UIButton的以下方法

+ (id)buttonWithType:(UIButtonType)buttonType {
    MyButton *toReturn = [super buttonWithType:buttonType];
    toReturn.imageView.contentMode = UIViewContentModeScaleAspectFit;
    return toReturn;
}

- (CGRect)imageRectForContentRect:(CGRect)contentRect {
    return contentRect;
}

And it works well.它运作良好。

Strange, the only combo that worked for me (iOS 5.1) is...奇怪的是,唯一对我有用的组合(iOS 5.1)是......

button.imageView.contentMode = UIViewContentModeScaleAspectFit;

and

[button setImage:newImage forState:UIControlStateNormal];

Just do (From Design OR From Code):只是做(从设计或从代码):

From Design从设计

  1. Open your xib OR Storyboard.打开您的 xib 或故事板。
  2. Select button选择按钮
  3. Inside Attribute Inspector (Right side) > In "Control" section > select last 4th option for both Horizontal and Verical.属性检查器内部(右侧)> 在“控制”部分> 为水平和垂直选择最后一个第四个选项

[For Point#3: Change Horizontal and vertical Align to UIControlContentHorizontalAlignmentFill and UIControlContentVericalAlignmentFill] [对于第 3 点:将水平和垂直对齐更改为UIControlContentHorizontalAlignmentFill and UIControlContentVericalAlignmentFill]

From Code从代码

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

I just ran into this same problem, and there's a possible answer in this question:我刚刚遇到了同样的问题,这个问题有一个可能的答案:

Why does a custom UIButton image does not resize in Interface Builder? 为什么自定义 UIButton 图像不会在 Interface Builder 中调整大小?

Essentially, use the backgroundimage property instead, which does get scaled.本质上,改用 backgroundimage 属性,它会被缩放。

From small test I just did after reading here, depends if you use setImage or setBackgroundImage, both did the same result and strech the image从我在这里阅读后刚刚做的小测试,取决于你是否使用 setImage 或 setBackgroundImage,两者都做了相同的结果并拉伸图像

//for setBackgroundImage
 self.imageButton.contentMode = UIViewContentModeScaleAspectFill;
        [self.imageButton setBackgroundImage:[UIImage imageNamed:@"imgFileName"] forState:UIControlStateNormal];

//for setImage
 self.imageButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
        self.imageButton.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
    [self.imageButton setImage:[UIImage imageNamed:@"imgFileName"] forState:UIControlStateNormal];

like this can solve your problem:像这样可以解决您的问题:

+ (UIImage*)resizedImage:(UIImage*)image
{
 CGRect frame = CGRectMake(0, 0, 60, 60);
 UIGraphicsBeginImageContext(frame.size);
 [image drawInRect:frame];
 UIImage* resizedImage = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();

 return resizedImage;
}
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
button.contentVerticalAlignment =  UIControlContentVerticalAlignmentFill;

Storyboard故事板

You must define specific property in Runtime Attributes of Identity inspectorimageView.contentModel , where you set value relatively to rawValue position of enum UIViewContentMode .运行时属性身份检查的,必须定义特定的属性- imageView.contentModel ,你设置的值相对于rawValue枚举的位置UIViewContentMode 1 means scaleAspectFit . 1 表示scaleAspectFit

在 Storyboard 中设置 button.imageView.contentMode

And button's alignment, in Attributes inspector :和按钮的对齐方式,在属性检查器中

按钮完全对齐

这也将起作用,因为 backgroundImage 会自动缩放

[button setBackgroundImage:image forState:UIControlStateNormal];

I hope this can help to somebody else:我希望这可以对其他人有所帮助:

Swift 3+斯威夫特 3+

button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.fill
button.contentVerticalAlignment =  UIControlContentVerticalAlignment.fill

I can't get a solution use by _imageView, but I can use a CGContextRef to solve it.我无法获得 _imageView 使用的解决方案,但我可以使用CGContextRef来解决它。 It use the UIGraphicsGetCurrentContext to get the currentContextRef and draw a image in currentContextRef, and then scale or rotate the image and create a new image.它使用UIGraphicsGetCurrentContext获取 currentContextRef 并在 currentContextRef 中绘制图像,然后缩放或旋转图像并创建新图像。 But it's not perfect.但它并不完美。

the code:编码:

-(UIImage*) scaleAndRotateImage:(UIImage*)photoimage width:(CGFloat)bounds_width height:(CGFloat)bounds_height;
{
    CGImageRef imgRef = photoimage.CGImage;

    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);

    CGAffineTransform transform = CGAffineTransformIdentity;
    CGRect bounds = CGRectMake(0, 0, width, height);

    bounds.size.width = bounds_width;
    bounds.size.height = bounds_height;

    CGFloat scaleRatio = bounds.size.width / width;
    CGFloat scaleRatioheight = bounds.size.height / height;
    CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
    CGFloat boundHeight;
    UIImageOrientation orient = photoimage.imageOrientation;
    switch(orient)
    {
        case UIImageOrientationUp: //EXIF = 1
            transform = CGAffineTransformIdentity;
            break;

        case UIImageOrientationUpMirrored: //EXIF = 2
            transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            break;

        case UIImageOrientationDown: //EXIF = 3
            transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;

        case UIImageOrientationDownMirrored: //EXIF = 4
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
            transform = CGAffineTransformScale(transform, 1.0, -1.0);
            break;

        case UIImageOrientationLeftMirrored: //EXIF = 5
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;

        case UIImageOrientationLeft: //EXIF = 6
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;

        case UIImageOrientationRightMirrored: //EXIF = 7
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeScale(-1.0, 1.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;

        case UIImageOrientationRight: //EXIF = 8
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;

        default:
            [NSException raise:NSInternalInconsistencyException format:@"Invalid?image?orientation"];
            break;
    }

    UIGraphicsBeginImageContext(bounds.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft)
    {
        CGContextScaleCTM(context, -scaleRatio, scaleRatioheight);
        CGContextTranslateCTM(context, -height, 0);
    }
    else
    {
        CGContextScaleCTM(context, scaleRatio, -scaleRatioheight);
        CGContextTranslateCTM(context, 0, -height);
    }

    CGContextConcatCTM(context, transform);

    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return imageCopy;
}

来自@JosephH

contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.fill contentVerticalAlignment = UIControl.ContentVerticalAlignment.fill

XCode 8 中的屏幕截图

At the bottom left of screenshot, you can see Stretching properties.在屏幕截图的左下角,您可以看到 Stretching 属性。 Try using those.尝试使用那些。

You can modify imageView by using custom class of UIButton.您可以使用 UIButton 的自定义类来修改 imageView。 Please see my answer.请看我的回答。 https://stackoverflow.com/a/59874762/5693826 https://stackoverflow.com/a/59874762/5693826

Every UIButton has one hidden UIImageView of its own.每个 UIButton 都有一个自己隐藏的 UIImageView。 So we have to set the content mode like the way given below...所以我们必须像下面给出的方式设置内容模式......

[[btn imageView] setContentMode: UIViewContentModeScaleAspectFit];
[btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM