我是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



例子2



有什么办法可以避免裁员吗?

最佳答案

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

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

关于android - 裁剪ShapeDrawable椭圆形(描边样式)的边缘(Android Studio),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44462844/

10-11 22:55
查看更多