Work around Canvas.clipPath() that is not supported in android any more

前端 未结 2 2122
自闭症患者
自闭症患者 2020-11-27 05:39

From android 3.0 the clipPath() method is no longer supported in devices with hardware acceleration turned on.(Read this article for more details).

I am working with

2条回答
  •  悲哀的现实
    2020-11-27 05:59

    Canvas.clipPath() support with hardware acceleration has been reintroduced since API 18.

    The best way to work around the problem is calling setLayerType(View.LAYER_TYPE_SOFTWARE, null) only when you are running on API from 11 to 17:

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2
            && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        setLayerType(LAYER_TYPE_SOFTWARE, null);
    }
    

    I also surrounded the clipPath() call with a try-catch block to avoid unpredicted app crashes:

    if (doClip) {
        try {
            canvas.clipPath(clipPath);
        } catch (UnsupportedOperationException e) {
            Log.e(TAG, "clipPath() not supported");
            doClip = false;
        }
    }
    

    Anyway, UnsupportedOperationException should never be thrown on API >= 18.

    See Unsupported Drawing Operations

提交回复
热议问题