1

我是 Android Studio 的新手,目前我正在尝试以编程方式创建一个随机颜色、笔触宽度和大小的椭圆形(不是实心,只是笔触):

        long randomSeedm = System.currentTimeMillis();
        Random random = new Random(randomSeedm);
        int[] color = {R.color.red, R.color.black, .....};

        int ovalWidth = 20 + random.nextInt(100);
        int ovalHeight = 20 + random.nextInt(100);

        ShapeDrawable shape = new ShapeDrawable(new OvalShape());
        shape.setIntrinsicWidth (ovalWidth);
        shape.setIntrinsicHeight (ovalHeight);
        shape.getPaint().setColor(getResources().getColor(color[random.nextInt(6)]));
        shape.getPaint().setStyle(Paint.Style.STROKE);
        shape.getPaint().setStrokeWidth(2+random.nextInt(15));
        shape.getPaint().setAntiAlias(true);

        ImageView oval = new ImageView(this);
        oval.setImageDrawable(shape);

在我将 ImageView 放入覆盖整个屏幕的 FrameLayout 之后:

        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ovalWidth, ovalHeight);
        left = random.nextInt(frameLayoutWidth - ovalWidth);
        top = random.nextInt(frameLayoutHeight - ovalHeight);
        params.leftMargin = left;
        params.topMargin = top;
        params.gravity = Gravity.TOP + Gravity.LEFT;

        frameLayoutWholeScreen.addView(oval, params);

结果非常令人满意(从我初学者的角度来看),唯一的问题是椭圆的边缘被部分切割。这里有些例子:

示例 1

[1]

示例 2

[2]

有什么办法可以避免割伤吗?

4

1 回答 1

1

在制作框架布局参数时,您需要添加笔画的值。

    int strokeSize = 2 + random.nextInt(15);
    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ovalWidth + strokeSize, ovalHeight + strokeSize);
    left = random.nextInt(frameLayoutWidth - (ovalWidth + strokeSize));
    top = random.nextInt(frameLayoutHeight - (ovalHeight + strokeSize));
    params.leftMargin = left;
    params.topMargin = top;
    params.gravity = Gravity.TOP + Gravity.LEFT;
    frameLayoutWholeScreen.addView(oval, params);
于 2017-06-10T02:47:46.360 回答