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!
I finally solved it by adding
self.imageView.frame = CGRectMake(4, 4, 32, 32);
to the- (void)layoutSubviews {}
method.So
have done it.