Android DP / SP to pixels

For some reason I always remember converting DP/SP into pixels as being a pain but with TypedValue.applyDimension it’s really easy. It is a bit verbose though so I’ve wrapped it in a Kotlin wrapper along with my other Android utils:

package net.samclarke.android

import android.content.Context
import android.util.TypedValue

object AndroidUtils {
    fun sp2px(value: Float, context: Context) =
            TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
                    value, context.resources.displayMetrics)

    fun dp2px(value: Float, context: Context) =
            TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                    value, context.resources.displayMetrics)
}

The more I use Kotlin the more I like it! I really hope it catches on outside of Android.

Comments