1

I'm new to Android Studio and at the moment I'm trying to create an oval (not solid, just stroke) of random color, stroke width and size programmatically:

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

Ater that I put the ImageView into a FrameLayout that covers the whole screen:

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

The results are very satisfying (from my beginner's point of view), the only problem is that the edges of the ovals are partially cut. Here are some examples:

Example 1

[1]

Example 2

[2]

Is there some way to avoid the cuts?

Omal Perera
  • 2,971
  • 3
  • 21
  • 26

1 Answers1

1

You need to add the value of the stroke when making the frame layout params.

    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);
KevinZ
  • 756
  • 1
  • 12
  • 26