jim
jim

Reputation: 49

Custom View: Canvas draw methods give API error

I created a custom view and overrode the onDraw method.

However, Android Studio says my canvas.drawOval and canvas.drawArc calls require I set my minimum API to 21.

Canvas has been around since API 1 right?

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.Button;

public class PieButton extends Button {

    float progress = 0f;

    public PieButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void onDraw(Canvas canvas) {
        Paint paint = new Paint();

        paint.setStyle(Paint.Style.FILL);
        paint.setColor(0xFF00C853);  
        canvas.drawOval(0, 0, getWidth(), getHeight(), paint);

        paint.setStyle(Paint.Style.FILL);
        paint.setColor(0xFF000000);
        canvas.drawArc(0, 0, getWidth(), getHeight(), 0f, progress*(-360), true, paint);
    }

    public void setProgress (float inputProgress) {
        progress = inputProgress;
    }
}

The error message I get is:

Call requires API level 21 (current min is 16): android.graphics.Canvas#drawOval less... (Ctrl+F1)

Upvotes: 2

Views: 3325

Answers (2)

Rohit
Rohit

Reputation: 2681

canvas.drawOval(0, 0, getWidth(), getHeight(), paint); is being added in API level 21. See API call here.

If you want to draw oval at api level minimum than 21 you should use it in following way,

RectF rect=new RectF(0, 0, getWidth(), getHeight());

public void drawOval (rect, paint);

Upvotes: 0

dishooom
dishooom

Reputation: 498

The drawOval() method that you are using from canvas was added in API 21.

public void drawOval (float left, float top, float right, float bottom, Paint paint) - API 21.

You should try using the drawOval() with RectF parameter, instead.

public void drawOval (RectF oval, Paint paint) - API 1

Same applies for drawArc(). Use drawArc with RectF parameter.

public void drawArc (RectF oval, float startAngle, float sweepAngle, boolean useCenter, Paint paint) - API 1

Upvotes: 15

Related Questions