Skip to content

Commit

Permalink
feat: added matrix effect
Browse files Browse the repository at this point in the history
  • Loading branch information
soo941226 committed Feb 15, 2022
1 parent 6a8a46c commit 250e295
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
76 changes: 76 additions & 0 deletions Core/ParticleEffect/MatrixEffect.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
//
// MatrixEffect.swift
// VEMTestProject
//
// Created by kjs on 2022/02/15.
//

#if os(iOS)
import UIKit

final class MatrixEffect: ParticleEffect {

func ready(with strings: [String]) {
setUpCells {
let images = strings.map { string in
return cgImage(from: styledLabel(with: string))
}

var texts = [CAEmitterCell]()

for image in images {
let text = CAEmitterCell()
text.contents = image
text.lifetime = 10.0
text.birthRate = 4.0

text.scale = 1.0
text.scaleRange = 0.6

text.velocity = -200.0
text.velocityRange = -150.0
texts.append(text)
}

return texts
}

setUpLayer { layer in
layer.emitterPosition = CGPoint(x: background.bounds.width / 2.0, y: -100)
layer.emitterSize = CGSize(width: background.bounds.width, height: 0)
layer.emitterShape = .line
layer.beginTime = CACurrentMediaTime()
}
}

private func styledLabel(with string: String) -> UILabel {
let breadthBasis = 30.0
let label = UILabel(frame: .init(
x: .zero,
y: .zero,
width: breadthBasis,
height: CGFloat(string.count) * breadthBasis
))

label.alpha = 0.85
label.textColor = .green
label.numberOfLines = .zero
label.adjustsFontSizeToFitWidth = true
label.font = .preferredFont(forTextStyle: .body)
label.text = string.map{ $0.description }.joined(separator: "\n")

return label
}

private func cgImage(from label: UILabel) -> CGImage? {
UIGraphicsBeginImageContext(label.frame.size)
var cgImage: CGImage?
if let context = UIGraphicsGetCurrentContext() {
label.layer.render(in: context)
cgImage = context.makeImage()
UIGraphicsEndImageContext()
}
return cgImage
}
}
#endif
5 changes: 5 additions & 0 deletions Core/ParticleEffect/Particle.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ public enum Particle {
case withSnow
case withBubble
case withBallon
case withMatrix(text: [String])

public func ready(for view: UIView) -> Runable {
switch self {
Expand All @@ -22,6 +23,10 @@ public enum Particle {
return BubbleEffect(for: view)
case .withBallon:
return BalloonEffect(for: view)
case .withMatrix(let strings):
let matrixEffect = MatrixEffect(for: view)
matrixEffect.ready(with: strings)
return matrixEffect
}
}
}
Expand Down

0 comments on commit 250e295

Please sign in to comment.