问题描述
我有一个CGSize
对象,需要将其发送到服务器.我可以发送到服务器的最大尺寸为900 * 900(900宽度/900高度).
I have a CGSize
objects that I need to send to my server. The maximum size I can send to the server is 900*900 (900 width/900 height).
有些对象的尺寸较大,为900 * 900,我想编写一个函数来将它们的尺寸调整为最大(正如我已经说过的,最大为900 * 900),但是要保持宽高比.
There are some objects that are larger the 900*900 and I want to write a function that resizes them to the maximum (as I already say, the maximum is 900*900) but to keep the aspect ratio.
例如:如果我有一个宽度为1,000px和高度为1,000px的对象,则我希望该函数返回900 * 900对象.如果我有一个宽度为1920px和高度为1080px的对象,我希望它返回尽可能大的尺寸并保持该比例.
For example: if I have an object that is 1,000px width and 1,000px height I want the function to return a 900*900 object. If I have an object that is 1920px width and 1080px height I want it to return the maximum size possible with keeping the ratio.
任何人都知道我该怎么做吗?
Anyone have any idea how can I do that?
谢谢!
OriginalUser2答案:
我尝试了以下代码:
let aspect = CGSizeMake(900, 900)
let rect = CGRectMake(0, 0, 1920, 1080)
let final = AVMakeRectWithAspectRatioInsideRect(aspect, rect)
final
是{x 420 y 0 w 1,080 h 1,080}
,我不明白为什么x = 420
,但是1080*1080
的宽高比与1920*1080
不同,并且比900*900
大.
final
is {x 420 y 0 w 1,080 h 1,080}
, I can't understand why the x = 420
, but anyway 1080*1080
is not in the same aspect ratio as 1920*1080
and it's bigger than 900*900
.
您能再解释一下吗?
推荐答案
您可以使用AVFounation框架中的AVMakeRect(aspectRatio:insideRect:)
函数来实现此目的.
You can use the AVMakeRect(aspectRatio:insideRect:)
function from the AVFounation framework in order to do this.
您的代码存在的问题是,这些值以错误的方式四舍五入. insideRect:
参数应为rect以适合您的尺寸,aspectRatio:
参数应为要在保持宽高比的同时缩放的原始尺寸.
The problem with your code is that the values are round the wrong way. The insideRect:
parameter should be the rect to fit your size within, and the aspectRatio:
should be the original size that you want to be scaled while maintaining aspect ratio.
例如:
import AVFoundation
// Original size which you want to preserve the aspect ratio of.
let aspect = CGSize(width: 1920, height: 1080)
// Rect to fit that size within. In this case you don't care about fitting
// inside a rect, so pass (0, 0) for the origin.
let rect = CGRect(x: 0, y: 0, width: 900, height: 900)
// Aspect fitted size, in this case (900.0, 506.25)
let result = AVMakeRect(aspectRatio: aspect, insideRect: rect).size
这篇关于在保持宽高比的情况下将CGSize调整为最大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!