关于ios:CAShapeLayer和SpriteKit

 2021-04-27 

CAShapeLayer and SpriteKit

我正在尝试使用SpriteKit中不可用的CAShapeLayer中的路径动画功能,因此必须将使用CAShapeLayer绘制的对象与SpriteKit对象合并在同一视图中。

坐标系似乎是相反的:CAShapeLayer的y轴指向下方,而SKScene的y轴指向上方。

下面是一个简单的XCODE运动场,它试图在0,0到200,100之间绘制一条黄线,并用较粗的红线对其进行阴影。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import SpriteKit
import PlaygroundSupport

let bounds = CGRect(x: 0, y: 0, width: 400, height: 200)
let view = SKView(frame: bounds)
view.backgroundColor = UIColor.lightGray

PlaygroundPage.current.liveView = view

// Create SK Scene
let scene = SKScene(size: CGSize(width: 400, height: 200))
scene.scaleMode = SKSceneScaleMode.aspectFit
view.presentScene(scene);

// Define the path
let path: CGMutablePath = CGMutablePath();
path.move(to: CGPoint(x:0, y:0))
path.addLine(to: CGPoint(x:200, y:100))

// Use CAShapeLayer to draw the red line
var pathLayer: CAShapeLayer = CAShapeLayer()
pathLayer.path = path  
pathLayer.strokeColor = UIColor.red.cgColor
pathLayer.fillColor = nil
pathLayer.lineWidth = 4.0
pathLayer.lineJoin = kCALineJoinBevel
pathLayer.zPosition = 1;
view.layer.addSublayer(pathLayer);

//Use SKShapeNode to draw the yellow line
let pathShape: SKShapeNode = SKShapeNode(path: path);
pathShape.strokeColor = .yellow;
pathShape.lineWidth = 1.0;
pathShape.zPosition = 10;
scene.addChild(pathShape);

我希望黄线与红线重合。而黄线和红线显示为镜像。

是否有重新定义CAShapeLayer坐标系以将ve Y轴指向上方的原因?


不,正如文档中所写的那样,它是如何工作的,您可以反转坐标以符合您的要求。.

Sprite套件文档:

The unit coordinate system places the origin at the bottom left corner of the frame and (1,1) at the top right corner of the frame. A sprite’s anchor point defaults to (0.5,0.5), which corresponds to the center of the frame.

iOS的其余部分:

iOS. The default coordinate system has its origin at the upper left of the drawing area, and positive values extend down and to the right from it. You cannot change the default orientation of a view’s coordinate system in iOS—that is, you cannot"flip" it.