请参阅以下代码。我想在屏幕的中心画一个矩形。但是它在左下角画了一个矩形。
protected void onDraw(Canvas canvas) {
paint.setColor(Color.GREEN);
canvas.drawRect(getLeft()/2,getTop()/2,getRight()/2,getBottom()/2,paint);
super.onDraw(canvas);
}
答案 0 :(得分:8)
那样的东西?
protected void onDraw(Canvas canvas) {
int canvasW = getWidth();
int canvasH = getHeight();
Point centerOfCanvas = new Point(canvasW / 2, canvasH / 2);
int rectW = 100;
int rectH = 100;
int left = centerOfCanvas.x - (rectW / 2);
int top = centerOfCanvas.y - (rectH / 2);
int right = centerOfCanvas.x + (rectW / 2);
int bottom = centerOfCanvas.y + (rectH / 2);
Rect rect = new Rect(left, top, right, bottom);
canvas.drawRect(rect, new Paint());
}
答案 1 :(得分:3)
答案 2 :(得分:2)
试试这个
protected void onDraw(Canvas canvas) {
paint.setColor(Color.GREEN);
canvas.drawRect(
getLeft()+(getRight()-getLeft())/3,
getTop()+(getBottom()-getTop())/3,
getRight()-(getRight()-getLeft())/3,
getBottom()-(getBottom()-getTop())/3,paint);
super.onDraw(canvas);
}