How to make a view with rounded corners?

前端 未结 20 1264
遇见更好的自我
遇见更好的自我 2020-11-27 11:08

I am trying to make a view in android with rounded edges. The solution I found so far is to define a shape with rounded corners and use it as the background of that view.

20条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 11:40

    Jaap van Hengstum's answer works great however I think it is expensive and if we apply this method on a Button for example, the touch effect is lost since the view is rendered as a bitmap.

    For me the best method and the simplest one consists in applying a mask on the view, like that:

    @Override
    protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
        super.onSizeChanged(width, height, oldWidth, oldHeight);
    
        float cornerRadius = ;
        this.path = new Path();
        this.path.addRoundRect(new RectF(0, 0, width, height), cornerRadius, cornerRadius, Path.Direction.CW);
    }
    
    @Override
    protected void dispatchDraw(Canvas canvas) {
        if (this.path != null) {
            canvas.clipPath(this.path);
        }
        super.dispatchDraw(canvas);
    }
    

提交回复
热议问题