大阪市中央区 システムソフトウェア開発会社

営業時間:平日09:15〜18:15
MENU

Kotlinで作るAndroidアプリ・・アナログ時計の回転針の修正

著者:川上洋
公開日:2019/08/01
最終更新日:2019/08/01
カテゴリー:技術情報 雑記

こんにちは。
Swift版でアナログ時計の作成後に、AndroidStudioのKotlinに彷徨っている川上です。

以前のKotlinでアナログ時計の回転針処理がヘンっだった件、は修正できました。

短針や長針、秒針の回転処理の正解は、
ImageView内のImageを回転しないで、ImageView自体を回転する」でした。。
NETでツマミ読みながらなので、あまり、深く考えずにKotlinを使っているので、まぁ、違いはそんなもんですw。
Swift版での処理は、鼻からImageView本体を回転していたのに、Kotlin処理の検索検討が間違いでした。
ImageView内のImageのややこしそうなMatrix処理の回転でなくて、単純にImageViewの回転で良かったのでした。。

短針、長針、秒針の回転処理は、以下同文ってな感じです。

 //--- 短時間針の表示
    fun updateHoure(hour :Int,minu:Int) {
        var imgHoure: ImageView? =  findViewById(R.id.short_hari)

        val bitmap1 = BitmapFactory.decodeResource(
            resources,
            R.drawable.short_hari
        )
        imgHoure!!.setImageBitmap(bitmap1)

        // 画像中心を基点に回転
        val degrees = CircleUtil.computeAngleByHour(hour,minu)
        imgHoure.setRotation(degrees)
    }
//--- 長針の表示
    fun updateMinur(minu:Int) {
        var imgMinture: ImageView? =  findViewById(R.id.long_hari)
     ・・ 省略・・
//         画像中心を基点に回転
        val degrees = CircleUtil.computeAngleByMinite(minu)
        imgMinture.setRotation(degrees)
    }

    //--- 秒針の表示
    fun updateSecond(secnd:Int) {
        var imgSecond: ImageView? =  findViewById(R.id.second_hari)
     ・・ 省略・・
        // 画像中心を基点に回転
        val degrees = CircleUtil.computeAngleByMinite(secnd)
        imgSecond.setRotation(degrees)
    }

--- 角度の取得I/F--
package com.example.timeclock.activity.MyUtil
object CircleUtil {
    private const val CIRCLE_RADIUS = 360

    // -- index番目の要素の角度を計算して返す
    fun computeAngleByIndex(partitions: Int, index: Int): Float {
        val angleUnit = (CIRCLE_RADIUS / partitions).toFloat()
        return index * angleUnit
    }

    // -- 分時間の角度を返す(長針、秒針)
    fun computeAngleByMinite(minute: Int): Float {
        val angleUnit = (CIRCLE_RADIUS / 60).toFloat()
        return minute * angleUnit
    }

     // -- 時間の角度を返す(短針)
    fun computeAngleByHour(hour: Int, minute: Int): Float {
        val angleUnit = CIRCLE_RADIUS.toFloat() / (12 * 60)
        return (hour * 60 + minute) * angleUnit
    }
}

以上、時計回転処理でした。。

ちなみに、iPhoneXRでのアナログ時計動作はコチラで、Swift版同様のKotlin版アナログ時計はこちらです。

ではでは。

    上に戻る