Custom Layout that rounds the corners of its content

后端 未结 7 2008
北海茫月
北海茫月 2020-11-29 04:08

I would like to create a generic ViewGroup which can then be reused in XML layouts to round the corners of anything that is put into it.

For some reason canvas

相关标签:
7条回答
  • 2020-11-29 04:32

    ViewGroup (and hence its subclasses) sets a flag indicating that it doesn't do any drawing by default. In source it looks somewhat like this:

    // ViewGroup doesn't draw by default
    if (!debugDraw()) {
        setFlags(WILL_NOT_DRAW, DRAW_MASK);
    }
    

    So your onDraw(...) probably doesn't get hit at all right now. If you want to do any manual drawing, call setWillNotDraw(false).

    0 讨论(0)
  • 2020-11-29 04:36

    Don't forget to ask for onDraw to be called with setWillNotDraw(false); and set a value to mRadius then just do something like that :

    @Override
    protected void onDraw(Canvas canvas) {
        mPath.reset();
        mRect.set(0, 0, canvas.getWidth(), canvas.getHeight());
        mPath.addRoundRect(mRect, mRadius, mRadius, Direction.CCW);
        mPath.close();
        canvas.clipPath(mPath);
    }
    
    0 讨论(0)
  • 2020-11-29 04:43

    onDraw of FrameLayout is not called if Ur Layout's background not set;

    You should override dispatchDraw;

    0 讨论(0)
  • 2020-11-29 04:45

    You can override the draw(Canvas canvas) method:

    
    
        public class RoundedLinearLayout extends LinearLayout {
            Path mPath;
            float mCornerRadius;
    
            public RoundedLinearLayout(Context context) {
                super(context);
            }
    
            public RoundedLinearLayout(Context context, AttributeSet attrs) {
                super(context, attrs);
            }
    
            public RoundedLinearLayout(Context context, AttributeSet attrs, int defStyle) {
                super(context, attrs, defStyle);
            }
    
            @Override
            public void draw(Canvas canvas) {
                canvas.save();
                canvas.clipPath(mPath);
                super.draw(canvas);
                canvas.restore();
            }
    
            @Override
            protected void onSizeChanged(int w, int h, int oldw, int oldh) {
                super.onSizeChanged(w, h, oldw, oldh);
                RectF r = new RectF(0, 0, w, h);
                mPath = new Path();
                mPath.addRoundRect(r, mCornerRadius, mCornerRadius, Direction.CW);
                mPath.close();
            }
    
            public void setCornerRadius(int radius) {
                mCornerRadius = radius;
                invalidate();
            }
          }
    
    
    0 讨论(0)
  • 2020-11-29 04:51

    The right way to create a ViewGroup that clip its children is to do it in the dispatchDraw(Canvas) method.

    This is an example on how you can clip any children of a ViewGroup with a circle:

    private Path path = new Path();
    
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    
        // compute the path
        float halfWidth = w / 2f;
        float halfHeight = h / 2f;
        float centerX = halfWidth;
        float centerY = halfHeight;
        path.reset();
        path.addCircle(centerX, centerY, Math.min(halfWidth, halfHeight), Path.Direction.CW);
        path.close();
    
    }
    
    @Override
    protected void dispatchDraw(Canvas canvas) {
        int save = canvas.save();
        canvas.clipPath(circlePath);
        super.dispatchDraw(canvas);
        canvas.restoreToCount(save);
    }
    

    the dispatchDraw method is the one called to clip children. No need to setWillNotDraw(false) if your layout just clip its children.

    This image is obtained with the code above, I just extended Facebook ProfilePictureView (which is a FrameLayout including a square ImageView with the facebook profile picture):

    So to achieve a round border you do something like this:

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    
        // compute the path
        path.reset();
        rect.set(0, 0, w, h);
        path.addRoundRect(rect, radius, radius, Path.Direction.CW);
        path.close();
    
    }
    
    @Override
    protected void dispatchDraw(Canvas canvas) {
        int save = canvas.save();
        canvas.clipPath(path);
        super.dispatchDraw(canvas);
        canvas.restoreToCount(save);
    }
    

    You can actually create any complex path :)

    Remember you can call clipPath multiple times with the "Op" operation you please to intersect multiple clipping in the way you like.

    NOTE: I created the Path in the onSizeChanged because doing so in the onDraw is bad for performance.

    NOTE2: clipping a Path is done without anti-aliasing :/ so if you want smooth borders you'll need to do it in some other way. I'm not aware of any way of making clipping use anti-aliasing right now.

    UPDATE (Outline)

    Since Android Lollipop (API 21) elevation and shadows can be applied to views. A new concept called Outline has been introduced. This is a path that tells the framework the shape of the view to be used to compute the shadow and other things (like ripple effects).

    The default Outline of the view is a rectangular of the size of the view but can be easily made an oval/circle or a rounded rectangular. To define a custom Outline you have to use the method setOutlineProvider() on the view, if it's a custom View you may want to set it in the constructor with your custom ViewOutlineProvider defined as inner class of your custom View. You can define your own Outline provider using a Path of your choice, as long as it is a convex path (mathematical concept meaning a closed path with no recess and no holes, as an example neither a star shape nor a gear shape are convex).

    You can also use the method setClipToOutline(true) to make the Outline also clip (and I think this also works with anti-aliasing, can someone confirm/refute in comments?), but this is only supported for non-Path Outline.

    Good luck

    0 讨论(0)
  • 2020-11-29 04:53

    U need to override the drawChild() method to clip childViews.

    @Override
    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
        int flag = canvas.save();
        canvas.clipPath(pathToClip);
        boolean result=super.drawChild(canvas, child, drawingTime);
        canvas.restoreToCount(flag);
        return result;
    }
    

    If u want to clip the background of the ViewGroup too,override draw() instead.like this

    @Override
    public void draw(Canvas canvas) {
        int flag = canvas.save();
        canvas.clipPath(pathToClip);
        super.draw(canvas);
        canvas.restoreToCount(flag);
    }
    
    0 讨论(0)
提交回复
热议问题