保持纵横比,将CGSize调整到最大

时间:2016-06-23 15:53:29

标签: objective-c c swift algorithm cocoa-touch

我有一个MATCH (e:Etg) WHERE e.mpc STARTS WITH 'Cardio' WITH e MATCH (p1:Provider)-[t1:TREATED]->(e)<-[t2:TREATED]-(p2:Provider) WHERE p1.specialty<>p2.specialty and p1.provSysId<p2.provSysId and abs(t1.servDt-t2.servDt)<=365 WITH p1, p2, count(distinct e.mbrSysId) as cnt WHERE cnt>5 RETURN p1.provSysId, p2.provSysId, cnt; 个对象需要发送到我的服务器。我可以发送到服务器的最大尺寸是900 * 900(900宽度/ 900高度)。

有些对象比900 * 900要大,我想编写一个函数来调整它们的最大值(正如我已经说过的,最大值是900 * 900)但要保持宽高比。

例如:如果我有一个宽度为1,000px且高度为1,000px的对象,我希望该函数返回一个900 * 900对象。如果我有一个1920px宽度和1080px高度的对象,我希望它能保持比率,尽可能返回最大尺寸。

任何人都知道我该怎么做?

谢谢!

OriginalUser2回答:

我已尝试过此代码:

CGSize

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 = 4201080*1080的宽高比不同它比1920*1080大。

你能解释一下吗?

2 个答案:

答案 0 :(得分:7)

您可以使用AVFounation框架中的AVMakeRect(aspectRatio:insideRect:)功能来执行此操作。

您的代码存在的问题是值是错误的。 insideRect:参数应该是适合您尺寸的矩形,aspectRatio:应该是您希望在保持宽高比时缩放的原始尺寸。

例如:

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

答案 1 :(得分:1)

这段代码可以大大减少和修改,但为了清楚起见:

def add(a, b):

    N = max(len(str(a)), len(str(b)))
    carry = 0

    x = [None] * N
    y = [None] * N
    r = [None] * (N + 1)

    for i in xrange(N):
        x[i], y[i] = a % 10, b % 10
        a, b = a / 10, b / 10

    for i in xrange(N):
        r[i] = (x[i] + y[i] + carry) % 10
        carry = (x[i] + y[i] + carry) / 10
    r[N] = carry

    return r


def addSimplified(a, b):

    N = max(len(str(a)), len(str(b))) + 1
    carry = 0

    r = [0] * N

    for i in xrange(N):
        step = (a / pow(10, i) % 10)  + (b / pow(10, i) % 10) + carry
        r[i] = step % 10
        carry = step / 10

    return r

print add(100, 20), addSimplified(100, 20)
print add(166, 66), addSimplified(166, 66)
print add(1920606,  9500666), addSimplified(1920606,  9500666)

在此代码段中,if myImage.width == myImage.height { // New image will be 900px by 900px newImage.width = (900 / myImage.width) * myImage.width newImage.height = (900 / myImage.height) * myImage.height } else if myImage.width > myImage.height { // New image will have width of 900px newImage.width = (900 / myImage.width) * myImage.width newImage.height = (900 / myImage.width) * myImage.height } else { // New Image will have height of 900px newImage.width = (900 / myImage.height) * myImage.width newImage.height = (900 / myImage.height) * myImage.height } 是已调整大小的图片的最大宽度和高度,但此值可以使用您想要的任何值的变量进行抽象。