ユニファ開発者ブログ

ユニファ株式会社プロダクトデベロップメント本部メンバーによるブログです。

ひらがな練習アプリを作ってみる

こんにちは。iOSエンジニアのキムです。ユニファの開発ブログでは初の投稿になります。よろしくお願いします。

私は4才の娘がいますが、娘が最近ひらがなに興味を持つようになり、読み書きの練習としてアプリを作ってあげることにしました。 今日はそのアプリについて簡単に紹介させていただきたいと思います。

準備

今回作ったアプリは、画面上にひらがなの文字が表示されて、指でなぞって線を描くようなシンプルなアプリです。あとは、画面に表示されている文字を音声で読み上げる機能も入れてみました。指でなぞって線を描く機能ではUIBezierPathを使っています。また、音声機能はAVSpeechSynthesizerを使っています。

処理内容

iOSでは指で画面をなぞることでタッチイベントが発生します。 今回はタッチイベント発生時にUIBezierPathを使って線を描画します。 以下のような流れになります。

touchesBegan(_:with:) タッチ開始時

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first?.location(in: self) {
        path = UIBezierPath()
        path?.lineWidth = 30
        path?.lineCapStyle = .round
        path?.lineJoinStyle = .round
        path?.move(to: touch)
    }
}

touchesMoved(_:with:) タッチしたまま指を移動

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first?.location(in: self) {
        path?.addLine(to: touch)
        setNeedsDisplay()
    }
}

touchesEnded(_:with:) タッチした指が離れる

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first?.location(in: self) {
        path.addLine(to: touch)
        setNeedsDisplay()
    }
}

AVSpeechSynthesizerを使ってテキストを読み上げる処理

func speak(string: String) {
    self.speechSynthesizer = AVSpeechSynthesizer()
    let utterance = AVSpeechUtterance(string: string)
    utterance.voice = AVSpeechSynthesisVoice(language: "ja-JP")
    utterance.rate = AVSpeechUtteranceMinimumSpeechRate
    utterance.pitchMultiplier = 1
    self.speechSynthesizer.speak(utterance)
}

// 利用方法
speak(string: "あ")

上記では日本語を指定していますが、指定がなければ端末の言語設定が適用されます。 また、声の高さや文字を読み上げるスピードなども変更できます。

イメージ

f:id:unifa_tech:20190722154745g:plain

最後に

子供に作ったアプリを見せたら大喜びで遊んでました。が、3日くらいで飽きてしまったようで今は使ってくれません・・・。 今後も子供のために何か面白いアプリを作ってあげたいなと思います。