Prevent UIButton.imageView from resizing by image

2019-08-26 08:10发布

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:

enter image description here

I have added the image like the following:

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

The result I'm getting is:

enter image description here

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条回答
戒情不戒烟
2楼-- · 2019-08-26 09:09

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.

查看更多
登录 后发表回答