Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImage Aspect Fill when using drawInRect?

Tags:

ios

swift

uiimage

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)))
like image 596
Lucy Jeong Avatar asked Nov 29 '22 22:11

Lucy Jeong


1 Answers

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.

like image 93
Nick Lockwood Avatar answered Dec 18 '22 17:12

Nick Lockwood