在屏幕中央绘制一个矩形

时间:2015-07-08 13:59:24

标签: android

请参阅以下代码。我想在屏幕的中心画一个矩形。但是它在左下角画了一个矩形。

protected  void onDraw(Canvas canvas) {
        paint.setColor(Color.GREEN);
        canvas.drawRect(getLeft()/2,getTop()/2,getRight()/2,getBottom()/2,paint);
        super.onDraw(canvas);
    }

3 个答案:

答案 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)

  1. 找到屏幕的中心 x =宽度/ 2.0 y =身高/ 2.0
  2. 计算矩形的左上角 topX = x - (rectWidth / 2.0) topY = y - (rectHeight / 2.0)

答案 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);
}