如何使用DPI缩放系数(浮点)设置页边距(INT) [英] How to use DPI scaling factor (float) to set margins (int)

查看:210
本文介绍了如何使用DPI缩放系数(浮点)设置页边距(INT)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Andr​​oid应用程序看起来不错,在480x800像素分辨率,但它打破在LDPI屏幕,240X400像素。我知道我可以使用 getResources()获取缩放屏幕的因子活性。getDisplayMetrics()。密度这将给出确切的浮动值取决于屏幕分辨率。

My Android app looks great at 480x800 pixels resolution but it breaks at LDPI screen with 240x400 pixels. I know I can get scaling factor of screen in activity using getResources().getDisplayMetrics().density which would give the exact float value depending upon screen resolution.

在我的应用程序,我已经使用 RelativeLayout的的ImageView 秒内它,并用设置图像的边缘 setMargins(),因为这种方法使用 INT 像素的上,左,底部和正确的价值观,<强>使用DPI因素我得到了我该怎么设置这些值?(这是一个浮点数)。我们有 Math.floor()但我使用像素的图像定位在非常特殊的位置,并通过方法返回的DPI因子在小数位非常具体的值不能被忽略,所以铸造 INT 不为我工作。

In my app, I have used RelativeLayout and ImageViews within it, and set the margins of images using setMargins(), as this method uses pixels in int for its top, left, bottom and right values, how can I set these values using DPI factor I got? (which is a float). We have Math.floor() but I'm positioning images at very particular locations using pixels, and DPI factor returned by method has very specific value at decimal places which can't be ignored, so casting to int doesn't work for me.

更新

另外,我用 lp.setMargins(100,200,0,0); 来设置页边距,什么样的修改,我会做它用DPI因子I从设备:收到?

Also, I use lp.setMargins(100,200,0,0); to set the margins, what modification I'll be making in it to use DPI factor I recieved from device?

P.S。我知道它更多的是数学问题,而不是编程,但我穷数学,不好意思。

P.S. I know its more a mathematical issue rather than programming, but I'm poor with math, sorry.

推荐答案

看起来好像我是太早要求,而不是摆弄自己的问题,但也注意到,我不是在所有的第一个要面对这个问题。

Looks like I was too early to ask the question instead of fiddling myself, but also noticed that I'm not AT ALL the first to face this issue.

所以,这里的解决方案,我发现了。

So, here's solution I found.

我在Activity类中创建一个下面的方法。

I created a following method in my Activity class.

private int px(float dips)
{
    float DP = getResources().getDisplayMetrics().density;
    return Math.round(dips * DP);
}

这会转化成给定 DP 值转换成相应的像素。你可以把这些变量 DP 的方法曾经是全球和在的onCreate()方法初始化它,而不是内 PX(),只是为了让execute方法快。

This would convert given dp value into appropriate pixels. You can make the variable DP used in method to be global and initialize it in your onCreate() method rather than within px(), just to make method execute fast.

用法:

lp.setMargins(px(100),px(200), 0, 0);

或者,如果你没有创建 PX()只是这一点,并有 DP 全球

OR, if you don't create px() just for this and have DP as global.

lp.setMargins(100 * Math.round(DP), 200 * Math.round(DP), 0, 0);

不过,使用方法,使得它看起来更加干净和可读性。 : - )

However, using method makes it look much cleaner and readable. :-)

这篇关于如何使用DPI缩放系数(浮点)设置页边距(INT)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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