canvas.drawRect如何绘制矩形

时间:2017-10-24 15:41:59

标签: android canvas android-view android-custom-view

我必须创建一个自定义视图,我必须绘制一个矩形。我试图使用canvas.drawRect方法。我想像这样enter image description here

创建一些矩形

灰色的是我的自定义视图,它扩展了View类。 在onDraw方法中,我试图绘制矩形。

但实际上我对drawRect方法的参数感到困惑。

根据文件

/**
 * Draw the specified Rect using the specified paint. The rectangle will
 * be filled or framed based on the Style in the paint.
 *
 * @param left   The left side of the rectangle to be drawn
 * @param top    The top side of the rectangle to be drawn
 * @param right  The right side of the rectangle to be drawn
 * @param bottom The bottom side of the rectangle to be drawn
 * @param paint  The paint used to draw the rect
 */

我假设左边和上边形成起点的x,y坐标,右边是宽度,底边是高度。但它似乎并没有这样做。

我尝试过这样的东西来绘制一个矩形,但它不会绘制任何东西

       paint.setColor(Color.BLUE);
       canvas.drawRect(5, canvas.getHeight()/2, 30, 30, paint );

任何人都可以告诉我们使用这些值绘制一个矩形的确切方式吗?

如果有人能够显示至少绘制第一个矩形的代码,那将非常有用。

我的要求是,内部矩形的数量是动态的,所以如果我将4个传递给这个视图,它应该水平创建4个相等宽度的矩形。像enter image description here

这样的东西

提前致谢!!

2 个答案:

答案 0 :(得分:6)

  

但实际上我对drawRect方法的参数感到困惑。

drawRect方法只需要两个坐标来绘制矩形。 左上角和右下角。所以4个点构成了这两个坐标 在你的画布上。希望从下面的图像中可以清楚地看到

enter image description here

P1和P2是由(左,上)和(右,下)形成的点,因此绘制的矩形将是这样的。

enter image description here

要像在图像中显示的那样动态绘制矩形,请尝试使用此类

int[] colors = new int[]{Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW}; // given some fixed colors
你在onDraw方法中

@Override
    protected void onDraw(Canvas canvas) {
    int padding = 5;
    float rectangleWidth = (getMeasuredWidth() - padding * 2) / colors.length;
    for (int i = 0; i < colors.length; i++) {
        paint.setColor(colors[i]);
        canvas.drawRect(padding + (rectangleWidth * i), getMeasuredHeight() / 2, padding + rectangleWidth * (i + 1), getMeasuredHeight() - padding, paint); // 5 px is the padding given to the canvas
    }
  }

答案 1 :(得分:2)

drawRect(float left, float top, float right, float bottom, Paint paint)

在您的情况下,问题是如果正确小于底部小于顶部然后不绘制矩形。但它似乎只在某些设备中发生,正如@David Medenjak评论

我还建议你使用View尺寸而不是Canvas尺寸,最好使用getWidth()&amp; getHeight()而不是Canvas.getWidth()&amp; Canvas.getHeight()

相关问题