gpt4 book ai didi

iOS Core Graphic,如何计算CGAffineTransform(scaleX offset?

转载 作者:行者123 更新时间:2023-11-28 10:27:59 26 4
gpt4 key购买 nike

当我通过 ray wenderlich 学习 Core Graphic 时,

一步是转换 UIBezierPath,var transform = CGAffineTransform(scaleX: 0.8, y: 0.8),

不知道为什么后面的步骤是transform = transform.translateBy(x: 15, y: 30)

我不知道 x 和 y 位置是如何计算出来的。

通过打印 UIBezierPath currentPoint print(medallionPath.currentPoint),我认为宽度应该是 (x1 - x2) * 0.5,高度应该是 y1 - y2,真不知道为什么会这样

(x: 15, y: 30)

完整代码如下,已在 Playground 中测试

let size = CGSize(width: 120, height: 200)
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let context = UIGraphicsGetCurrentContext()!

//Gold colors
let darkGoldColor = UIColor(red: 0.6, green: 0.5, blue: 0.15, alpha: 1.0)
let midGoldColor = UIColor(red: 0.86, green: 0.73, blue: 0.3, alpha: 1.0)

let medallionPath = UIBezierPath(ovalIn: CGRect(x: 8, y: 72, width: 100, height: 100))

print(medallionPath.currentPoint)
// (108.0, 122.0)
print(medallionPath.bounds)
// (8.0, 72.0, 100.0, 100.0)
context.saveGState()
medallionPath.addClip()

darkGoldColor.setFill()
medallionPath.fill()

context.restoreGState()
// question
var transform = CGAffineTransform(scaleX: 0.8, y: 0.8)

// transform = transform.translatedBy(x: 15, y: 30)
medallionPath.lineWidth = 2.0

//apply the transform to the path
medallionPath.apply(transform)
print(medallionPath.currentPoint)
// (86.4, 97.6)
print(medallionPath.bounds)
// (6.4, 57.6, 80.0, 80.0)
medallionPath.stroke()


//This code must always be at the end of the playground
let image = UIGraphicsGetImageFromCurrentImageContext()!

UIGraphicsEndImageContext()

最佳答案

transform = transform.translatedBy(x: 15, y: 30)

是一个翻译。它将整个路径向右移动 15向下 30 .您的问题是魔数(Magic Number) 15 在哪里?和 30来自。


奖章图有一个尺寸为 100 的圆x 100从位置 (8, 72) 开始由这行代码建立:

let medallionPath = UIBezierPath(ovalIn: CGRect(x: 8, y: 72, width: 100, height: 100))

代码然后通过将原始路径缩放 0.8 添加一个内环, 所以它将是一个 80 x 80圆圈。为了让这个小圆环的中心与大圆的中心对齐,它需要额外偏移 10在水平和垂直方向上。 (较小的圆圈是 20 水平和垂直较小,因此将它移动 1/220 使其正确对齐)。然后目标是将其定位在 (18, 82)。与 width: 80, height: 80 .

因此,我们需要在 X 和 Y 方向上应用平移(移动),以便在缩放路径时我们最终得到锚定在 (18, 82) 的路径。 .棘手的一点是缩放应用于移位值,因此也必须考虑到这一点。

因此,我们从 8 的 X 位置开始, 我们想应用一些翻译值 dx这样当结果按 0.8 缩放时我们最终得到值 18 :

(8 + dx) * 0.8 = 18

求解dx :

dx = (18 / 0.8) - 8
dx = 14.5

与 Y 类似,我们从 72 的 Y 位置开始并想申请翻译 dy这样当它按 0.8 缩放时我们最终得到 82 :

(72 + dy) * 0.8 = 82

求解dy :

dy = (82 / 0.8) - 72
dy = 30.5

因此,数学上正确的翻译是 (14.5, 30.5) :

transform = transform.translatedBy(x: 14.5, y: 30.5)

Ray Wenderlich 四舍五入为 (15, 30)由于某些只有他们知道的原因(也许是因为整数在代码中看起来更好?)。有可能他们没有费心做数学运算,只是尝试值直到它看起来正确

关于iOS Core Graphic,如何计算CGAffineTransform(scaleX offset?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57841983/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com