我使用的是Nexus 7 1280×800
android 4.2.2 API 17
我想得到屏幕的大小,将其划分为相同高度和宽度的方形部分.
我正在使用FrameLayout,我的正方形是ImageView的子类.
我这样做
context.getResources()getDisplayMetrics()heightPixels.; —-> 1205
context.getResources()getDisplayMetrics()像素宽度.; ——> 800
我认为1205不是1280,因为屏幕的顶部和底部有两个Android菜单.
我的每个方块都是30×30像素.
要知道我可以绘制多少个正方形作为最大值:
int x = 1205/30;
当我尝试在坐标(x-1)* 30上绘制我的图像时,它会部分地从屏幕上绘制出来.
我怎么知道我的应用程序可以使用的屏幕部分?
我希望我能很好地解释我的问题.
非常感谢.
解决方法
如果所有的方块都在同一个ImageView中,那么我猜最简单的方法是创建自己的imageView:
class MyImageView extends ImageView { Context context; int myWidth = 0; int myHeigh = 0; int numBoxesX = 0; int numBoxesY = 0; private final int BoxWidth = 30; private final int BoxHeight = 30; ImageView(Context c) { super(c); context = c; } }
在类中,您重写onSizeChange函数
@Override protected void onSizeChanged (int w,int h,int oldw,int oldh) { super.onSizeChanged(w,h,oldw,oldh); myWidth = w; myHeight = h; // Set up other things that you work out from the width and height here,such as numBoxesX = myWidth / BoxWidth; numBoxesY = myHeight / BoxHeight; }
然后创建一个绘制框的函数:
public void drawSubBox(int x,int y,...) { // Fail silently if the Box being drawn doesn't exist ... if ((x<0) || (x>=numBoxesX)) return; if ((y<0) || (y>=numBoxesY)) return; // Your code to draw the Box on the screen ... }
创建此视图后,您可以将其添加到布局中,并像访问任何其他视图一样访问它的功能,包括您添加的任何内容以定义子框的大小等等.因此,在此类的活动中使用此布局
MyImageView miv; miv = topView.findViewById("idforMyImageViewSetInLayoutXMLfile"); miv.drawSubBox(0,...);