在屏幕中心绘制一个矩形。

5
请看以下代码。我想在屏幕中央画一个矩形,但它画在左上角。
protected  void onDraw(Canvas canvas) {
        paint.setColor(Color.GREEN);
        canvas.drawRect(getLeft()/2,getTop()/2,getRight()/2,getBottom()/2,paint);
        super.onDraw(canvas);
    }

考虑视图的左/上/右/下 0/0/100/100,那么矩形将为 0/0/50/50,现在你知道这是为什么了吗? - pskink
5个回答

15

像这样吗?

    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());
    }

int bottom = centerOfCanvas.y + (rectH / 2); 底部 = 画布中心点.y + (矩形高度 / 2); - Giorgio
@Tronum 有没有办法让这个矩形拥有圆角? - K.Os

7

试试这个

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

4
  1. Find the center of the screen

    x = width / 2.0
    y = height / 2.0
    
  2. Calculate the top left corner of your rect

    topX = x - (rectWidth / 2.0)
    topY = y - (rectHeight / 2.0)
    

1

测试答案:

 override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        val canvasCenter = PointF(width/2f,height/2f)
        val rectW = 300f
        val rectH = 300f
        val rect = RectF(canvasCenter.x - rectW,canvasCenter.y -rectH,
            canvasCenter.x + rectW,canvasCenter.y + rectH)
        canvas?.drawRect(rect,mPaintDest)
    }

0
    var rectWidth = 200f
    var rectHeight = 300f

    val left = (width-rectWidth)/2
    val top = (height-rectHeight)/2
    val right = left+rectWidth
    val bottom = top+rectHeight

    canvas.drawRect(left, top, right, bottom, paint)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接