简体   繁体   中英

Getting Canvas.drawPaint not supported error while running an android app

I'm using canvas in my android code. It is as given below:

public class RecognitionScoreView extends View {
    private static final float TEXT_SIZE_DIP = 24;
    private List<Recognition> results;
    private final Paint fgPaint;
    private final Paint bgPaint;

    private static String TAG = RecognitionScoreView.class.getSimpleName();

    public RecognitionScoreView(final Context context, final AttributeSet set) {
        super(context, set);

        float textSizePx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, TEXT_SIZE_DIP, getResources().getDisplayMetrics());
        fgPaint = new Paint();
        fgPaint.setTextSize(textSizePx);

        bgPaint = new Paint();
        bgPaint.setColor(0xcc4285f4);
    }

    public void setResults(final List<Recognition> results) {
        this.results = results;
        Log.i(TAG, "setResults: Results are " + results);
        postInvalidate();
    }

    @Override
    public void onDraw(final Canvas canvas) {
        final int x = 10;
        int y = (int) (fgPaint.getTextSize() * 1.5f);

        canvas.drawPaint(bgPaint);

        if (results != null) {
            for (final Recognition recog : results) {
                canvas.drawText(recog.getTitle(), x, y, fgPaint);
                Log.i(TAG, "onDraw: Object is -- " + recog.getTitle());
                Log.i(TAG, "onDraw: Object location is -- " + recog.getLocation());
                Log.i(TAG, "onDraw: Object id is -- " + recog.getId());
                y += fgPaint.getTextSize();
            }
        }
       /* if (results != null) {
            Intent intent = new Intent(context, ResultActivity.class);
            context.this.startActivity(intent);

        }*/
    }
}  

When I run my code, I get this error:

Canvas.drawPaint is not supported. (Ignore for this session) How to fix this?

change your constructor to

public RecognitionScoreView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, set);

    float textSizePx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, TEXT_SIZE_DIP, getResources().getDisplayMetrics());
    fgPaint = new Paint();
    fgPaint.setTextSize(textSizePx);

    bgPaint = new Paint();
    bgPaint.setColor(0xcc4285f4);
}

I think problem with bgPaint, in some situation your constructor isn't called. As a result bgPaint == null , if you override last constrctructor in chain, than bgPaint will be inited

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM