获取屏幕尺寸以像素为单位 [英] Get screen dimensions in pixels
问题描述
我创建了一些自定义的元素,我希望以编程它们放置在右上角( N
从顶部边缘像素和 M
从右侧边缘像素)。因此,我需要得到屏幕宽度和屏幕的高度,然后设置位置:
INT PX =屏幕宽度 - 米;
INT PY = screenHeight - N;
我如何获得屏幕宽度
和 screenHeight
的主要活动?
如果你想在像素的显示尺寸,你可以使用<一个href="http://developer.android.com/reference/android/view/Display.html#getSize%28android.graphics.Point%29"><$c$c>getSize$c$c>:
显示显示= getWindowManager()getDefaultDisplay()。
点大小=新的点();
display.getSize(大小);
INT宽度= size.x;
INT高= size.y;
如果你不是在活动
就可以得到默认的显示
通过 WINDOW_SERVICE
:
窗口管理WM =(窗口管理器)context.getSystemService(Context.WINDOW_SERVICE);
显示显示= wm.getDefaultDisplay();
在的getSize
引入(在API级别13),你可以使用的getWidth
和的getHeight
是现在去precated方法:
显示显示= getWindowManager()getDefaultDisplay()。
INT宽度= display.getWidth(); //德precated
INT高= display.getHeight(); //德precated
有关使用情况,你要描述然而,保证金/填充布局似乎更为合适。
22 2015年10月
另一种方式是:<一href="http://developer.android.com/reference/android/util/DisplayMetrics.html">DisplayMetrics
描述有关显示器的一般信息,如它的大小,密度和字体缩放的结构。要访问DisplayMetrics成员初始化对象是这样的:
DisplayMetrics指标=新DisplayMetrics();
。getWindowManager()getDefaultDisplay()getMetrics(度量)。
我们可以使用 widthPixels
来获取信息:
像素显示的绝对宽度。
示例:
Log.d(ApplicationTagName,在PX显示宽度+ metrics.widthPixels);
I created some custom elements, and I want to programmatically place them to the upper right corner (n
pixels from the top edge and m
pixels from the right edge). Therefore I need to get the screen width and screen height and then set position:
int px = screenWidth - m;
int py = screenHeight - n;
How do I get screenWidth
and screenHeight
in the main Activity?
If you want the display dimensions in pixels you can use getSize
:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
If you're not in an Activity
you can get the default Display
via WINDOW_SERVICE
:
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Before getSize
was introduced (in API level 13), you could use the getWidth
and getHeight
methods that are now deprecated:
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth(); // deprecated
int height = display.getHeight(); // deprecated
For the use case you're describing however, a margin/padding in the layout seems more appropriate.
22 October 2015
Another ways is: DisplayMetrics
A structure describing general information about a display, such as its size, density, and font scaling. To access the DisplayMetrics members, initialize an object like this:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
We can use widthPixels
to get information for:
"The absolute width of the display in pixels."
Example:
Log.d("ApplicationTagName", "Display width in px is " + metrics.widthPixels);
这篇关于获取屏幕尺寸以像素为单位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!