I tried to draw scaleAspectFill like contents mode.
I found how to make sacelAspectFit using AVFoundation But I can't find scaleAspectFill.
if I draw horizontal image, I don't know x value
image.draw(in: CGRect(origin: CGPoint.init(x: ?, y: 0), size: CGSize(width: displayWidth*(image.size.width/image.size.height), height: displayWidth)))
Assuming you have an image called image
, and you want to draw it inside a rectangle targetRect
so that it fills the rect without being distorted, you can use the following code:
let aspect = image.size.width / image.size.height
let rect: CGRect
if targetRect.size.width / aspect > targetRect.size.height {
let height = targetRect.size.width / aspect
rect = CGRect(x: 0, y: (targetRect.size.height - height) / 2,
width: targetRect.size.width, height: height)
} else {
let width = targetRect.size.height * aspect
rect = CGRect(x: (targetRect.size.width - width) / 2, y: 0,
width: width, height: targetRect.size.height)
}
image.draw(in: rect)
Note: this doesn't clip the image, so it will draw outside the edges of the target rect. if you want to clip the image, call CGContextClipToRect(context, rect)
before drawing.
Note also that the core graphics vertical axis is flipped, with zero starting in the bottom-left instead of top-left compared to UIGraphics, so you may need to flip the rect and clipping rect accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With