androidround-rect

How to drawRoundRect() if Build.VERSION.SDK_INT < 21?


The method canvas.drawRoundRect()is only available on devices with Build.VERSION.SDK_INT >= 21.

The method canvas.drawArc() also requires SDK_INT >= 21.

Is it possible to drawRoundRect on older devices?


Solution

  • Yes. According the official docs: https://developer.android.com/reference/android/graphics/Canvas#drawRoundRect(android.graphics.RectF,%20float,%20float,%20android.graphics.Paint)

    There are two versions of drawRoundRect. The for lower apis(<21) accepts Rect as param.

    So you can do something like this:

    @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            Paint paint = new Paint();
            paint.setStyle(Paint.Style.FILL);
            paint.setColor(Color.RED);
            paint.setAntiAlias(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                canvas.drawRoundRect(0, 0, 0, 0, 2f, 3f, paint);
            } else {
                RectF rect = new RectF(10, 10, 20, 20);
                canvas.drawRoundRect(rect, 0, 0, paint);
            }
        }
    

    Change the values according to your use-case.