简体   繁体   中英

UIImage Aspect Fill when using drawInRect?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM