CGAffineTransform 仅缩放宽度和高度

CGAffineTransform to scale width and height only

如何在不影响原点的情况下缩放 CGontext,即只缩放宽度和高度?如果我直接使用下面的比例,它也会缩放原点。

context.scaledBy(x: 2.0, y: 2.0)

有没有一种方法可以构造一个 AffineTransform 来操纵宽度和高度,同时保持原点不变?

我想要一个可同时用于 CGContextCGRect 的 AffineTransform。

例如CGRect rect = {x, y, w, h}

var t = CGAffineTransform.identity
t = t.scaledBy(x: sx, y: sy)
let tRect = rect.applying(t)

tRect 将是 {x * sx, y * sy, w * sx, h * sy}

但是我想要{x, y, w * sx, h * sy}。虽然可以通过计算实现,但我需要CGAffineTransform来实现。

您需要平移原点,然后缩放,然后撤消平移:

import Foundation
import CoreGraphics

let rect = CGRect(x: 1, y: 2, width: 3, height: 4) // Whatever

// Translation to move rect's origin to <0,0>
let t0 = CGAffineTransform(translationX: -rect.origin.x, y: -rect.origin.y)
// Scale - <0,0> will not move, width & height will
let ts = CGAffineTransform(scaleX: 2, y: 3) // Whatever
// Translation to restore origin
let t1 = CGAffineTransform(translationX: rect.origin.x, y: rect.origin.y)

//Compound transform:
let t = t0.concatenating(ts).concatenating(t1)

// Test it:
let tRect = rect.applying(t) // 1, 2, 6, 12 as required