scale to fit image in swift

To scale an image to fit within a specific size in Swift, you can use the scaleAspectFit content mode of UIImageView.

Here's how you can do it:

main.swift
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
imageView.contentMode = .scaleAspectFit
imageView.image = UIImage(named: "yourImage")

// Add the image view to your view hierarchy
view.addSubview(imageView)
239 chars
7 lines

In the above code, we create a UIImageView instance, set its frame to the desired size, and set its content mode to scaleAspectFit. This content mode scales the image proportionally to fit within the imageView's bounds while maintaining its aspect ratio. Then, we set the image property to the desired image.

Finally, we add the image view to our view hierarchy by calling addSubview on the parent view (view in this case).

This way, the image will be automatically scaled to fit within the specified size defined by the frame of the UIImageView.

related categories

gistlibby LogSnag