Prevent UIButton.imageView from resizing by image

跟風遠走 提交于 2020-01-17 02:31:27

问题


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. 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. The imageView has a final size of 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.

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. How can I give the buttons imageView a fixed size with UIViewContentModeScaleAspectFit for the image.

thx a lot!


回答1:


I finally solved it by adding self.imageView.frame = CGRectMake(4, 4, 32, 32); to the - (void)layoutSubviews {} method.

So

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

have done it.



来源:https://stackoverflow.com/questions/52721194/prevent-uibutton-imageview-from-resizing-by-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!