问题
I'm fairly new to swift and I'm currently trying to display multiple image views within a custom UITableCell.
Ideally, I would like to have each image be scaled so that its width fills half of the screen size (while preserving the original aspect ratio).
The idea is that each UITableCell will have a collage of 3 images and some additional information in a UILabel -- the tallest image would sit in its own column with the smaller two stacked right next to the tallest. Below is a screenshot to help illustrate what I'm trying to achieve:

However, I'm having some trouble with this. Currently, once I've retrieved an image with an Alamofire .GET request, I call a function that does the below:
let aspectRatio = image.size.width / image.size.height
let newHeight = desiredWidth / aspectRatio
UIGraphicsBeginImageContext(CGSizeMake(desiredWidth, newHeight))
image.drawInRect(CGRectMake(0, 0, desiredWidth, newHeight))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
Once the image is returned, before adding it to the first image view, I update the frame of the image view as follows:
cell.img_1.frame = CGRect(x: 0, y: 0, width: new_image.size.width, height: new_image.size.height)
cell.img_1.image = new_image
However, when I run the code, the width of the images is not half of the screen-- rather- they look exactly the same as they would if I put them into the image view without scaling (the ImageView is set to Aspect Fit Mode).
When I print out the width and height of the newly scaled images the values ARE consistent with what I want.
I do notice that the pre-scale and post-scale aspect ratios are slightly off by ~.01. -- so given that the image view is set to Aspect Fit, could this explain what I am seeing?
I've also tried this with the mode set as Aspect Fill, but saw cases where the width of some images do not get scaled down properly, and take up more than half of the screen.
Apologies for the long-winded question, would greatly appreciate some help with this and I will provide more information if needed. Thank you!
回答1:
the ImageView is set to Aspect Fit Mode).
But there's your problem - or one of them. If you don't want an image view to resize the image, don't use any "aspect" content mode, nor any "fit" or "fill" content mode. Use, for example, Center.
来源:https://stackoverflow.com/questions/30180514/rescale-image-so-width-is-half-the-size-of-screen