From 250e295998f78134848bbdb838c31e21920776e3 Mon Sep 17 00:00:00 2001 From: soo941226 <83933153+soo941226@users.noreply.github.com> Date: Tue, 15 Feb 2022 22:43:23 +0900 Subject: [PATCH] feat: added matrix effect --- Core/ParticleEffect/MatrixEffect.swift | 76 ++++++++++++++++++++++++++ Core/ParticleEffect/Particle.swift | 5 ++ 2 files changed, 81 insertions(+) create mode 100644 Core/ParticleEffect/MatrixEffect.swift diff --git a/Core/ParticleEffect/MatrixEffect.swift b/Core/ParticleEffect/MatrixEffect.swift new file mode 100644 index 0000000..1a7889d --- /dev/null +++ b/Core/ParticleEffect/MatrixEffect.swift @@ -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 diff --git a/Core/ParticleEffect/Particle.swift b/Core/ParticleEffect/Particle.swift index 43ab6e0..617ebad 100644 --- a/Core/ParticleEffect/Particle.swift +++ b/Core/ParticleEffect/Particle.swift @@ -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 { @@ -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 } } }