An example code in Swift to create a grey button which shows fireworks when pressed:
main.swift1852 chars54 lines
In the viewDidLoad
, we create a UIButton
with a grey background color and add it to the view. We also set an action for the button when it is pressed, namely the function buttonPressed
.
In the buttonPressed
function, we create a CAEmitterLayer
to display the fireworks effect. We set the emitter position to be at the top center of the screen and the emitter shape to be a line. We also set the size of the emitter to match the width of the screen and a small height of 2 points.
We then create three different cells, each with a different color (red, green, blue) using the makeEmitterCell
function. We set the properties of each cell, such as the velocity, lifetime, color, and other properties to achieve the desired effect.
We add the three cells to the emitter and then add the emitter to the view's layer. Finally, we use DispatchQueue.main.asyncAfter
to remove the emitter layer after 1 second, so we don't leave any artifacts on the screen.
The makeEmitterCell
function creates and returns a CAEmitterCell
with the desired properties. We set the birth rate to 5 particles per second, the lifetime to 1 second, and no lifetime range. We set the color to match the parameter passed in, and the velocity to 200 points per second with a range of +/- 50 points. The emission range is set to a quarter of a circle (45 degrees). We also set the spin, scale, and contents properties to achieve the desired effect of the particle.
Note that we assume there is an image called "circle" that we're using as the contents of the particle cell. This image can be any shape or image you desire.
gistlibby LogSnag