圆形画出屏幕尺寸

时间:2017-12-12 21:14:55

标签: android canvas drawing

有人可以解释我如何设置画布不会在屏幕外画圆圈吗?

在屏幕截图中,它看起来像这样 - Click here to see image

正如你所看到的,有些圆圈在屏幕外面一半,但我希望所有圆圈都在屏幕内。

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Random random = new Random();
        int minRadius = 50;
        int w = this.getWidth();
        int h = this.getHeight();
        Paint paint = new Paint();

        for (int i=0; i<resultInt; i++) {
            int red = (int) (Math.random() * 255);
            int green = (int) (Math.random() * 255);
            int blue = (int) (Math.random() * 255);
            int randX = random.nextInt(w);
            int randY = random.nextInt(h);
            int color = Color.rgb(red, green, blue);
            paint.setColor(color);
            canvas.drawCircle(randX, randY, minRadius, paint);
        }
    }
}
}

2 个答案:

答案 0 :(得分:0)

你必须减去双半径:

 int w = this.getWidth() - 2 * minRadius;
 int h = this.getHeight() - 2 * minRadius;

然后修复随机点:

 int randX = random.nextInt(w) + minRadius;
 int randY = random.nextInt(h) + minRadius;

答案 1 :(得分:0)

int w = this.getWidth() - minRadius * 2;
int h = this.getHeight() - minRadius * 2;
...
int randX = random.nextInt(w) + minRadius;
int randY = random.nextInt(h) + minRadius;