How to create a 'transparent circle inside rectangle' shape in XML in Android?

后端 未结 3 799
臣服心动
臣服心动 2020-12-02 21:55

I\'m trying to create the following design in my app.

Design Mockup

Its an overlay on top of the main UI. Trying to create this using a layout on top o

3条回答
  •  攒了一身酷
    2020-12-02 22:18

    I ran into such a problem that code does not work on api lvl 16 from NSimon. I fixed the code and now it supports api 16+.

    public class FocusView extends View {
        private Paint mPaint;
        private Paint mStrokePaint;
        private Path mPath = new Path();
    
        public FocusView(Context context) {
            super(context);
            initPaints();
        }
    
        public FocusView(Context context, AttributeSet attrs) {
            super(context, attrs);
            initPaints();
        }
    
        public FocusView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            initPaints();
        }
    
        private void initPaints() {
            mPaint = new Paint();
            mPaint.setColor(Color.parseColor("#A6000000"));
    
            mStrokePaint = new Paint();
            mStrokePaint.setColor(Color.YELLOW);
            mStrokePaint.setStrokeWidth(2);
            mStrokePaint.setStyle(Paint.Style.STROKE);
    
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            mPath.reset();
    
            float radius = 0;
            float strokeWidth = 0;
            if (canvas.getWidth() < canvas.getHeight()) {
                radius = canvas.getWidth() / 2 - 10;
                strokeWidth = (canvas.getHeight() - canvas.getWidth())/2;
            } else {
                radius = canvas.getHeight() / 2 - 10;
                strokeWidth = (canvas.getWidth() - canvas.getHeight())/2;
            }
    
            mPaint.setStrokeWidth(strokeWidth);
    
            mPath.addCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, radius, Path.Direction.CW);
            mPath.setFillType(Path.FillType.INVERSE_EVEN_ODD);
    
            canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, radius, mStrokePaint);
    
            canvas.drawPath(mPath, mPaint);
        }
    }
    

提交回复
热议问题