androidkotlinandroid-canvasandroidxandroid-compatibility

Canvas clipOutRect compatibility in AndroidX


I recently came across the deprecation of clipRect(Rect,Region.Op), which I would like to use with DIFFERENCE. This was replaced with clipOutRect(Rect) and thus I implemented:

@Suppress("DEPRECATION")
fun clipOutRect(canvas: Canvas, rect: Rect) =
    if (SDK_INT >= O) canvas.clipOutRect(rect)
    else canvas.clipRect(rect, DIFFERENCE)

Now this looks like it could be a compatibility method in AndroidX, but for some reason I was not able to figure out, where I could find it exactly.

Is there a class already providing a compatibility method for clipOutRect(Rect)?


Solution

  • Short answer is - no. The only thing related to Canvas in AndroidX is this file: https://github.com/aosp-mirror/platform_frameworks_support/blob/androidx-master-dev/core/core-ktx/src/main/java/androidx/core/graphics/Canvas.kt

    Long answer. First of all, Canvas is passed to view by native code, so it will be awkward to have something like onDrawCompat(canvas: CanvasCompat) in ViewCompat class. And I think there is no reason to do that at all. Also, it's really not that type of deprecation you should worry about. For example WifiManager.startScan() is noted with

    This method was deprecated in API level 28. The ability for apps to trigger scan requests will be removed in a future release.

    That says Change this code now, or it will be broken year later

    That not the case with clipRect, it will be kept for backward compatibility with apps that won't be ever updated for years or even tenth of years. Deprecation warning for this is just like Hey, we have new method with better functionality/name, if you target minimum is API 26 you can use that