我有一个项目,我正在尝试绘制矩形以填充屏幕
MainActivity.java
public class MainActivity extends Activity {
private int vScreenHeight, vScreenWidth;
private int vLeftPos = 0;
private int vTopPos = 0;
private int vRightPos = 154;
private int vBottomPos = 154;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
vGetScreenHeightAndWidth();
while(vTopPos < vScreenHeight) {
while(vLeftPos < vScreenWidth) {
RectView rectView = new RectView(getApplicationContext(), vLeftPos, vTopPos, vRightPos, vBottomPos);
vLeftPos += 154;
vRightPos += 154;
setContentView(rectView);
}
vLeftPos = 0;
vTopPos += 154;
vRightPos = 154;
vBottomPos += 154;
}
}
private void vGetScreenHeightAndWidth() {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size); // this will work only in API level 13 above.
vScreenWidth = size.x;
vScreenHeight = size.y;
}
}
RectView.java
public class RectView extends View implements OnClickListener
{
private int vLeftPos;
private int vTopPos;
private int vRightPos;
private int vBottomPos;
Rect r;
private Paint paint = new Paint();
private final String TAG = "Canvas Application";
public RectView(Context pAppContext, int pLeftPos, int pTopPos, int pRightPos, int pBottomPos)
{
super(pAppContext);
vLeftPos = pLeftPos;
vTopPos = pTopPos;
vRightPos = pRightPos;
vBottomPos = pBottomPos;
r = new Rect();
this.setOnClickListener(this);
}
public void onDraw(Canvas pCanvasObj)
{
r.set(vLeftPos, vTopPos, vRightPos, vBottomPos);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
pCanvasObj.drawRect(r, paint);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.BLACK);
pCanvasObj.drawRect(r, paint);
}
@Override
public void onClick(View v)
{
Toast.makeText(null, "tapped", Toast.LENGTH_SHORT).show();
}
}
在这个Activity中,我正在计算矩形的位置并创建一个RectView对象来绘制矩形。
我无法理解我做错了什么?
答案 0 :(得分:0)
问题出在RectView
。你可以试试这个:
public class RectView extends View {
private RectF rect;
private Paint paint;
/**
* @param context
*/
public RectView(Context context) {
super(context);
paint=new Paint();
paint.setColor(Color.RED);
rect=new RectF();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
rect.set(0, 0, MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec));
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec));
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(rect, paint);
}