我正在尝试使用
我的问题是,我希望所有代码都包含在
SpriteKit
来动态绘制路径上的线条。我已经使用SKActions
和一个单独的CABasicAnimations
实现了一个可行的解决方案。但是SKAction
的解决方案并不太优雅;它会在每次SKAction.repeatAction(action:count:)
调用的迭代中创建并描绘一条新路径,每个新路径略微比之前更完整。func start() {
var i:Double = 1.0
let spinAction:SKAction = SKAction.repeatAction(SKAction.sequence([
SKAction.runBlock({
self.drawCirclePercent(i * 0.01)
if (++i > 100.0) {
i = 1.0
}
}),
SKAction.waitForDuration(0.01)
]), count: 100)
runAction(spinAction)
}
func drawCirclePercent(percent:Double) {
UIGraphicsBeginImageContext(self.size)
let ctx:CGContextRef = UIGraphicsGetCurrentContext()
CGContextSaveGState(ctx)
CGContextSetLineWidth(ctx, lineWidth)
CGContextSetRGBStrokeColor(ctx, 1.0, 1.0, 1.0, 1.0)
CGContextAddArc(ctx, CGFloat(self.size.width/2.0), CGFloat(self.size.height/2.0), radius/2.0, CGFloat(M_PI * 1.5), CGFloat(M_PI * (1.5 + 2.0 * percent)), 0)
CGContextStrokePath(ctx)
let textureImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
texture = SKTexture(image: textureImage)
UIGraphicsEndImageContext()
}
虽然上面的代码可以工作,但它肯定不够美观或高效,并且可能不是SKActions
的预期使用方式。使用CABasicAnimation
解决方案更加优雅和高效。
let path:CGMutablePathRef = CGPathCreateMutable()
CGPathAddArc(path, nil, 0, 0, 40.0, CGFloat(M_PI_2 * 3.0), CGFloat(M_PI_2 * 7.0), false)
let pathLayer:CAShapeLayer = CAShapeLayer()
pathLayer.frame = CGRectMake(100, 100, 80.0, 80.0)
pathLayer.path = path
pathLayer.strokeColor = SKColor.whiteColor().CGColor
pathLayer.fillColor = nil
pathLayer.lineWidth = 3.0
self.view.layer.addSublayer(pathLayer)
let pathAnimation:CABasicAnimation = CABasicAnimation(keyPath: "strokeEnd")
pathAnimation.duration = 2.0
pathAnimation.fromValue = 0.0
pathAnimation.toValue = 1.0
pathLayer.addAnimation(pathAnimation, forKey: "strokeEndAnimation")
我的问题是,我希望所有代码都包含在
SKSpriteNode
的子类中(如果上述两种解决方案是我的唯一选择,我会选择第一种方案)。是否有任何方法可以改进我的SKAction
实现,使其更接近CoreAnimation实现,而无需包括CoreAnimation
?本质上,我想知道SpriteKit是否具有我不知道的功能,可以用来改进第一种实现方式。
SKShader
,那么你可以在你的着色器 GLSL 代码中访问的变量之一是沿路径的弧长。 - rickster