使用drawInRect时UIImage Aspect填充? [英] UIImage Aspect Fill when using drawInRect?

查看:26
本文介绍了使用drawInRect时UIImage Aspect填充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试绘制类似内容模式的 scaleAspectFill.

I tried to draw scaleAspectFill like contents mode.

我找到了如何使用 AVFoundation 制作 sacelAspectFit 但我找不到 scaleAspectFill.

I found how to make sacelAspectFit using AVFoundation But I can't find scaleAspectFill.

如果我画水平图像,我不知道 x 值

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)))

推荐答案

假设您有一个名为 image 的图像,并且您想将其绘制在一个矩形 targetRect 中,因此它填充矩形而不会失真,您可以使用以下代码:

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)

注意:这不会裁剪图像,因此它会在目标矩形的边缘之外绘制.如果要裁剪图片,请在绘制前调用CGContextClipToRect(context, 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.

还要注意,核心图形的垂直轴是翻转的,与 UIGraphics 相比,零从左下角开始,而不是从左上角开始,因此您可能需要相应地翻转矩形和裁剪矩形.

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.

这篇关于使用drawInRect时UIImage Aspect填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆