为什么在缩放时 CAShapeLayer 不以我的 UIView 为中心?
Why is CAShapeLayer not centering to my UIView when I scale it?
let centerPointX = colorSizeGuide.bounds.midX / 2
let centerPointY = colorSizeGuide.bounds.midY / 2
let circleWidth: CGFloat = 10
let circleHeight: CGFloat = 10
shape.path = UIBezierPath(ovalIn: CGRect(x: centerPointX + circleWidth / 4, y: centerPointY + circleHeight / 4, width: circleWidth, height: circleHeight)).cgPath
shape.strokeColor = UIColor(r: 160, g: 150, b: 180).cgColor
shape.fillColor = UIColor(r: 160, g: 150, b: 180).cgColor
shape.anchorPoint = CGPoint(x: 0.5, y: 0.5)
shape.lineWidth = 0.1
shape.transform = CATransform3DMakeScale(4.0, 4.0, 1.0)
colorSizeGuide.layer.addSublayer(shape)
这是正在发生的事情。我需要 CAShapeLayer 留在小灰色区域的中间:
我自己在仿射变换方面有些挣扎,但我认为这是正在发生的事情:
缩放以 0,0 为中心,因此它将从该点开始扩展。这意味着它将 "push away" 来自原点。
为了从中心增长,您应该将原点移动到形状的中心点,缩放,然后将原点移回现在缩放的数量:
var transform = CATransform3DMakeTranslation(centerPointX, centerPointY, 0)
transform = CATransformScale(transform, 4.0, 4.0, 1.0)
var transform = CATransform3DTranslate(
transform,
-4.0 * centerPointX,
-4.0 * centerPointY,
0)
shape.transform = transform
顺便说一句,我无法理解你在问题中发布的图片。你说 "I need the CAShapeLayer to stay in the middle of the small gray area" 我知道你的形状图层是圆圈之一,但不清楚你的意思 "the small gray area." 看起来可能有一个轮廓以某种方式被裁剪了。
let centerPointX = colorSizeGuide.bounds.midX / 2
let centerPointY = colorSizeGuide.bounds.midY / 2
let circleWidth: CGFloat = 10
let circleHeight: CGFloat = 10
shape.path = UIBezierPath(ovalIn: CGRect(x: centerPointX + circleWidth / 4, y: centerPointY + circleHeight / 4, width: circleWidth, height: circleHeight)).cgPath
shape.strokeColor = UIColor(r: 160, g: 150, b: 180).cgColor
shape.fillColor = UIColor(r: 160, g: 150, b: 180).cgColor
shape.anchorPoint = CGPoint(x: 0.5, y: 0.5)
shape.lineWidth = 0.1
shape.transform = CATransform3DMakeScale(4.0, 4.0, 1.0)
colorSizeGuide.layer.addSublayer(shape)
这是正在发生的事情。我需要 CAShapeLayer 留在小灰色区域的中间:
我自己在仿射变换方面有些挣扎,但我认为这是正在发生的事情:
缩放以 0,0 为中心,因此它将从该点开始扩展。这意味着它将 "push away" 来自原点。
为了从中心增长,您应该将原点移动到形状的中心点,缩放,然后将原点移回现在缩放的数量:
var transform = CATransform3DMakeTranslation(centerPointX, centerPointY, 0)
transform = CATransformScale(transform, 4.0, 4.0, 1.0)
var transform = CATransform3DTranslate(
transform,
-4.0 * centerPointX,
-4.0 * centerPointY,
0)
shape.transform = transform
顺便说一句,我无法理解你在问题中发布的图片。你说 "I need the CAShapeLayer to stay in the middle of the small gray area" 我知道你的形状图层是圆圈之一,但不清楚你的意思 "the small gray area." 看起来可能有一个轮廓以某种方式被裁剪了。