iOS - 如何在iOS上实现类似粒子的动画效果

时间:2017-05-29 08:33:41

标签: ios swift canvas particles

我在运球时看到了许多网站和应用程序设计概念的粒子散射效应。效果如下: - https://www.craftedbygc.com/

效果也可以看作如以下链接所示: - https://dribbble.com/shots/3511585-hello-dribbble

我们如何在iOS应用程序中实现这样的效果?

2 个答案:

答案 0 :(得分:4)

如果您正在寻找简单的内容,请查看CAEmitterLayerCAEmitterCell。只需使用CAEmitterLayer emitterShape进行kCAEmitterLayerRectangle,然后您可以使用另一个CAShapeLayer裁剪它以获得所需的形状:

enter image description here

这是一个生成类似上述内容的示例:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    // define emitter layer as centered w 80% of smallest dimension

    let image = emitterImage
    let side = min(view.bounds.width, view.bounds.height) * 0.8
    let origin = CGPoint(x: view.bounds.midX - side / 2, y: view.bounds.midY - side / 2)
    let center = CGPoint(x: view.bounds.midX, y: view.bounds.midY)
    let size = CGSize(width: side, height: side)
    let rect = CGRect(origin: origin, size: size)
    let emitterLayer = CAEmitterLayer()
    emitterLayer.emitterShape = kCAEmitterLayerRectangle
    emitterLayer.emitterSize = rect.size
    emitterLayer.emitterPosition = center

    // define cells

    let cell = CAEmitterCell()
    cell.birthRate = Float(size.width * size.height / 10)
    cell.lifetime = 1
    cell.velocity = 10
    cell.scale = 0.1
    cell.scaleSpeed = -0.1
    cell.emissionRange = .pi * 2
    cell.contents = image.cgImage
    emitterLayer.emitterCells = [cell]

    // add the layer

    view.layer.addSublayer(emitterLayer)

    // mask the layer

    let lineWidth = side / 8
    let mask = CAShapeLayer()
    mask.fillColor = UIColor.clear.cgColor
    mask.strokeColor = UIColor.white.cgColor
    mask.lineWidth = lineWidth
    mask.path = UIBezierPath(arcCenter: center, radius: (side - lineWidth) / 2, startAngle: .pi / 4, endAngle: .pi * 7 / 4, clockwise: true).cgPath
    emitterLayer.mask = mask
}

var emitterImage: UIImage {
    let rect = CGRect(origin: .zero, size: CGSize(width: 10, height: 10))
    UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
    #colorLiteral(red: 0.5725490451, green: 0, blue: 0.2313725501, alpha: 1).setFill()
    UIBezierPath(arcCenter: CGPoint(x: rect.midX, y: rect.midY), radius: rect.midX, startAngle: 0, endAngle: .pi * 2, clockwise: true).fill()
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image!
}

我不知道任何简单的方式来制作与您的示例完全相同的内容,但您会在那里找到第三方库/演示(例如http://flexmonkey.blogspot.co.uk/2015/01/computing-particle-systems-in-swift.html)。

答案 1 :(得分:1)

SpriteKit是一个不错的选择。它有一个名为粒子发射器的功能。很多教程你会发现只有like this才能产生这样的效果