使用drawInRect时UIImage Aspect填充?

编程入门 行业动态 更新时间:2024-10-28 13:21:52
本文介绍了使用drawInRect时UIImage Aspect填充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我尝试绘制类似内容模式的 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-29 04:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1183967.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:drawInRect   UIImage   Aspect

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!