The following thread scale Image in an UIButton to AspectFit? discusses several ways to preserve image aspect ratio when scaling a button.
In fact just button.imageView!.contentMode = UIViewContentMode.ScaleAspectFit
does the job when target image size is bigger than the actual resource image size. However, if the resource image is bigger than target, ScaleAspectFit applies to the image, while imageView size remains unchanged, with unused areas on both sides of the image, so that the text doesn't have a room.
in the following code I tried to scale the image manually and assign it the the imageView of the button. Then the imageView size also changes to match the size of the image. I put prints to make sure that the image is scaled correctly, and the new frame size is accepted. I disabled "Autoresize subviews" for the button, but nothing helped: with ScaleAspectFit there are still blank spots, without - the image is "squashed":
let img = imageView.image!
var ivFrame = imageView.frame
println("Image view Frame Size Original: \(ivFrame.size.width)x\(ivFrame.size.height)")
let imgScaled = scaleImage(img,
CGSize(width: ivFrame.size.height, height: ivFrame.size.height))
imageView.image = imgScaled
let imageSize = imgScaled.size
println("Image Size Scaled: \(imageSize.width)x\(imageSize.height)");
imageView.frame = CGRectMake(imageView.frame.origin.x, imageView.frame.origin.y,
imageSize.width, imageSize.height)
ivFrame = imageView.frame;
println("Image view Frame Size New: \(ivFrame.size.width)x\(ivFrame.size.height)");
imageView.backgroundColor=UIColor.redColor() // to see image area
Console output:
Image view Frame Size Original: 90.0x39.0
Image Size Scaled: 39.0x39.0
Image view Frame Size New: 39.0x39.0