LoginSignup
226
224

More than 5 years have passed since last update.

電波っぽいアニメーションを3行で追加する「Pulsator」の使い方と実装解説

Last updated at Posted at 2016-04-11

パルス的なアニメーションを簡単に追加できるOSSです。

マップの現在値とか、iBeaconのビーコンとか、BLE(Bluetooth Low Energy)デバイスとか、そういう電波を発する系の表現に便利です。

動かすところまで一瞬でできる ので、自分でも各種案件で使用している他、ハッカソンやちょっとしたサンプルプロジェクトとかでも重宝してます。

言語はSwift、ライセンスはMITです。

v0.2.0 で Swift 3 サポートしました。

使い方

最短で3行で追加できます。

1. 初期化する

let pulsator = Pulsator()

2. ビューに追加する

表示したいビューの layer に追加します。

view.layer.addSublayer(pulsator)

3. アニメーションを開始する

pulsator.start()

カスタマイズ

半径、色、パルスの数 etc. をカスタマイズできます。同梱のデモプロジェクト・Playground をご参照ください。

  • Example/PulsatorDemo.xcodeproj
  • Pulsator.playground

ブラウザ上でも試せます

インストール方法

プロジェクトへのインストールはCocoaPods、Carthageをサポートしています。

Podfile
pod "Pulsator"
Cartfile
github "shu223/Pulsator"

利用例

このライブラリの前身(Objective-C版)であるPulsingHaloは、個人的にかなりの実案件やサンプルプロジェクトで利用してます。

whill.gif

moff.gif

  • BONX
    • トーク中の音声を示す波
  • とあるビーコン案件

    • マップ上で、ビーコン設置を示すAnnotationに使用
  • iOS-9-Sampler

    • Force Touch の位置と強さの可視化
    • ReplayKit のサンプルでも利用

forcetouch.gif

ObjC版についての解説記事(古いです)

実装解説

本OSSは全面的に Core Animation を利用した実装となっています。

CAReplicatorLayer

まず、親クラスは CAReplicatorLayer となっています。

public class Pulsator: CAReplicatorLayer

CAReplicatorLayer は instanceCount個のサブレイヤーの複製を作成するレイヤーで、本OSSではパルスを複数生成するのに利用しています。

The replicator layer creates a specified number of copies of its sublayers

CAAnimationGroup

各パルスのアニメーションは、拡大アニメーション + 不透明度のアニメーション を組み合わせたもので、それらを CAAnimationGroup で統合して実行しています。

let scaleAnimation = CABasicAnimation(keyPath: "transform.scale.xy")
// 略

let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
// 略

animationGroup = CAAnimationGroup()
animationGroup.animations = [scaleAnimation, opacityAnimation]

macOSでの利用

0.5.0より、macOSでも使えるようになりました🎉

Podfileにpod "Pulsator"を追加するだけ。

Podfile
platform :osx, '10.9'

target 'Pulsator' do
  use_frameworks!
  pod "Pulsator"
end

使い方はiOSと同じです。

let pulsator = Pulsator()
view.layer?.addSublayer(pulsator)
pulsator.start()

こちらがコードの差分なのですが、publicなAPI的には変更はありません1


  1. Pulsatorやその前身となるPulsing Haloをつくった当時、macOSサポートまで考慮してなかったのですが、UIViewベースではなく、CALayerベースにしておいて良かったです。。 

226
224
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
226
224