如果所有方块都在同一个 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 ...
}
创建此视图后,您可以将其添加到布局中,并像任何其他视图一样访问它的功能,包括您添加的任何用于定义子框大小等的功能。所以在 Activity 的类中使用这个布局
MyImageView miv;
miv = topView.findViewById("idforMyImageViewSetInLayoutXMLfile");
miv.drawSubBox(0,0, ...);