android-将dp转换为无上下文的px

android-将dp转换为无上下文的px,第1张

概述有一种非常巧妙的方法可以将dp转换为不带Context的px,它就像这样:publicstaticintdpToPx(intdp){floatdensity=Resources.getSystem().getDisplayMetrics().density;returnMath.round((float)dp*density);}在每个Google的GoogleGitHubpage示例中,他们

有一种非常巧妙的方法可以将dp转换为不带Context的px,它就像这样:

public static int dptopx(int dp) {    float density = Resources.getSystem().getdisplayMetrics().density;    return Math.round((float) dp * density);}

在每个Google的Google GitHub page示例中,他们都使用以下方法:

public static int convertDptopixel(Context ctx, int dp) {    float density = ctx.getResources().getdisplayMetrics().density;    return Math.round((float) dp * density);}

那么第一种方法有什么问题吗?对我来说,它在我所有的应用程序中都能正常工作,但是我想知道在某些情况下它可能会失败吗?

解决方法:

is there some case where it might fail?

就在这里!

AndroID支持不同的屏幕,例如,您可以使用Chromecast投射应用程序或通过其他方式连接到其他屏幕.在这种情况下,这些值将无法正确转换到该其他屏幕.

从documentation for Resources.getSystem():

Return a global shared Resources object that provIDes access to only
system resources (no application resources), and is not configured for
the current screen (can not use dimension units, does not change based
on orIEntation, etc).

总结

以上是内存溢出为你收集整理的android-将dp转换为无上下文的px全部内容,希望文章能够帮你解决android-将dp转换为无上下文的px所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1091340.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存