简体   繁体   English

防止UIButton.imageView按图像调整大小

[英]Prevent UIButton.imageView from resizing by image

I have a UIButton with a fixed height of 40 (constraint height of 40) where I set an image via code thats an pdf (vectorgraphic) of size 64x64 . 我有一个固定高度为40(约束高度为40)的UIButton ,其中我通过代码(即64x64的pdf(矢量图形))设置了图像。 The result should be: 结果应为:

在此处输入图片说明

I have added the image like the following: 我添加了如下图像:

image = [UIImage imageNamed:@"icon-clear"];
[self setImage:image forState:UIControlStateNormal];

The result I'm getting is: 我得到的结果是:

在此处输入图片说明

Added a black border to the imageView for better visualisation. imageView添加了黑色边框,以实现更好的可视化效果。 The imageView has a final size of 64x40 . imageView具有64x40的最终大小。

The thing that happen, I guess, is that the imageView gets the image and will be resized to 64x64 and downsized by button constraints to 40 again but reserves the width of 64. 我猜发生的事情是imageView会获取图像,并将其调整为64x64的大小,并通过按钮约束再次将其缩小为40,但保留64的宽度。

I tried multiple things: 我尝试了多种方法:

self.imageView.frame = CGRect(0,0,32,32);
self.imageView.bounds = CGRect(0,0,32,32);

or 要么

let aspectRatioConstraint = [NSLayoutConstraint constraintWithItem:self.imageView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.imageView attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0];
[self.imageView addConstraint:aspectRatioConstraint];

or 要么

[self.imageView.widthAnchor constraintEqualToConstant:32];

The only thing that made a visual change was: 进行视觉更改的唯一内容是:

UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *destImage = UIGraphicsGetImageFromCurrentImageContext();    
UIGraphicsEndImageContext();

but ended up in bad imagequality and I guess high performance issues. 但最终导致图像质量差,我猜想是高性能问题。

I just want to use the pdf vector file on multiple size situations. 我只想在多种尺寸的情况下使用pdf矢量文件。 How can I give the buttons imageView a fixed size with UIViewContentModeScaleAspectFit for the image. 如何给按钮imageView提供固定大小的图像,以及UIViewContentModeScaleAspectFit

thx a lot! 多谢!

I finally solved it by adding self.imageView.frame = CGRectMake(4, 4, 32, 32); 我终于通过添加self.imageView.frame = CGRectMake(4, 4, 32, 32);解决了它self.imageView.frame = CGRectMake(4, 4, 32, 32); to the - (void)layoutSubviews {} method. - (void)layoutSubviews {}方法。

So 所以

- (void)layoutSubviews {
    [super layoutSubviews];
    self.imageView.contentMode = UIViewContentModeScaleAspectFit;
    self.imageView.frame = CGRectMake(4, 4, 32, 32);
}

have done it. 已经做到了。

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

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