How to use android canvas to draw a Rectangle with only topleft and topright corners round?

前端 未结 15 2432
后悔当初
后悔当初 2020-11-29 01:58

I found a function for rectangles with all 4 corners being round, but I want to have just the top 2 corners round. What can I do?

canvas.drawRoundRect(new Re         


        
15条回答
  •  悲&欢浪女
    2020-11-29 02:21

    One simple and efficient way to draw a solid side is to use clipping - rect clipping is essentially free, and a lot less code to write than a custom Path.

    If I want a 300x300 rect, with the top left and right rounded by 50 pixels, you can do:

    canvas.save();
    canvas.clipRect(0, 0, 300, 300);
    canvas.drawRoundRect(new RectF(0, 0, 300, 350), 50, 50, paint);
    canvas.restore();
    

    This approach will only work for rounding on 2 or 3 adjacent corners, so it's a little less configurable than a Path based approach, but using round rects is more efficient, since drawRoundRect() is fully hardware accelerated (that is, tessellated into triangles) while drawPath() always falls back to software rendering (software-draw a path bitmap, and upload that to be cached on the GPU).

    Not a huge performance issue for small infrequent drawing, but if you're animating paths, the cost of software draw can make your frame times longer, and increase your chance to drop frames. The path mask also costs memory.

    If you do want to go with a Path-based approach, I'd recommend using GradientDrawable to simplify the lines of code (assuming you don't need to set a custom shader, e.g. to draw a Bitmap).

    mGradient.setBounds(0, 0, 300, 300);
    mGradient.setCornerRadii(new int[] {50,50, 50,50, 0,0, 0,0});
    

    With GradientDrawable#setCornerRadii(), you can set any corner to be any roundedness, and reasonably animate between states.

提交回复
热议问题