如何在Android Jetpack Compose中将Dp转换为像素? [英] How to convert Dp to pixels in Android Jetpack Compose?

查看:257
本文介绍了如何在Android Jetpack Compose中将Dp转换为像素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大多数Jetpack Compose API使用 Dp 作为尺寸单位,但有时需要像素值.如何将dp值转换为px?仅作为示例,有一个 graphicsLayer() translationX/Y 参数的修饰符.

Most of Jetpack Compose API uses Dp as a dimensions unit, but sometimes a pixel value is required. How can I convert a dp value to px? Just for an example there's graphicsLayer() modifier that accepts translationX/Y arguments in pixels.

推荐答案

There're toPx() and roundToPx() methods defined by Density interface, you can use it like this:

import androidx.compose.ui.platform.LocalDensity

val pxValue = with(LocalDensity.current) { 16.dp.toPx() }

// or

val pxValue = LocalDensity.current.run { 16.dp.toPx() }

如果您是Kotlin语言的新手,那么这种表达式可能会令人困惑,因此让我们对其进行分解,看看它是如何工作的. toPx()扩展功能 Dp 类,可以将其视为 Dp 类方法.但是,由于 toPx()是在密度界面,除非您提供密度作为接收器,否则无法使用它.最后,您可以从名为 CompositionLocal 的当前密度中获取 LocalDensity .

Such an expression might look confusing if you're new to Kotlin language so let's break it down and see how it works. toPx() is an extension function of Dp class, you can think of it as a Dp class method. But since toPx() is defined inside Density interface, you cannot use it unless you provide a density as a receiver. And at last you can get the current density from an CompositionLocal named LocalDensity.

这篇关于如何在Android Jetpack Compose中将Dp转换为像素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆