问题
I have an image looking like this

But it should look like this :

I added the line : cameraUIButton.imageView?.contentMode = .scaleAspectFit
It doesn't works BUT if i click on the button it fit !! What append in swift when you click on the button that recalculate the fit of the image ?
I already tried
cameraUIButton.setNeedsDisplay()
cameraUIButton.imageView?.setNeedsDisplay()
cameraUIButton.imageView?.layoutIfNeeded()
cameraUIButton.layoutIfNeeded()
self.view.layoutIfNeeded()
and all in
viewDidLoad()
viewWillAppear()
viewDidAppear()
Nothing do what cliking on the button do, what else could i try ?
回答1:
When you do cameraUIButton.imageView?.contentMode = .scaleAspectFit
it ensures that the image is scaled so as to fit the frame of the view, button in this case.
Try cameraUIButton.imageView?.contentMode = .aspectFit
it will retain original image and not stretch it.
回答2:
I found the solution !!
You need to add
cameraUIButton.imageView?.adjustsImageSizeForAccessibilityContentSizeCategory = true
So the full code to aspectFit a vector image inside a button is :
cameraUIButton.imageView?.contentMode = .scaleAspectFit
cameraUIButton.imageView?.adjustsImageSizeForAccessibilityContentSizeCategory = true
I don't know why it's not true
by default as it's turned to it if you click on the button or if you animate it.
回答3:
Try this way
button.contentHorizontalAlignment = .fill
button.contentVerticalAlignment = .fill
button.imageView?.contentMode = .scaleAspectFit
回答4:
- Go on storyboard give it a fixed width and height
- give is horizontal or vertical constraint according to your view.
- if you do these step you will get your image, also it will work fine in all device, don't forget to check clipOutOfBounds
来源:https://stackoverflow.com/questions/57904427/aspectfit-image-inside-an-uibutton