Repository navigation
[Android] Draw BoxView and shapes without creating Java paints and paths - #40902
Conversation
Drawing a BoxView on Android created about 21 Java Paint objects, two Java Paths and three PathF objects for every draw. When a CollectionView rebinds a row, its BoxView gets a new color and is drawn again, so this was about 13% of the UI thread's time and 40% of the bytes it allocated per row (with #40881). Microsoft.Maui.Graphics (Android): - PlatformCanvas reuses canvas states instead of disposing them: AbstractCanvas releases states through a hook that PlatformCanvas overrides to return them to its PlatformCanvasStateService, which copies the default or saved state into a released state's Java paints (Paint.Set) instead of creating new ones. - PlatformCanvas.ResetState no longer replaces the paints of the state it has just created with new copies of the same defaults. - PlatformCanvas converts paths into one Android Path that it reuses, and converts again only when it gets a different path, a changed path (PathF has an internal version that Invalidate, which every change calls, increments) or a different scale. Filling the path it clipped to reuses the conversion. - ScalingCanvas passes its scale to PlatformCanvas instead of creating a scaled copy of every path (only for PlatformCanvas itself, as subclasses can override FillPath, ClipPath and PlatformDrawPath). - AsAndroidPath no longer allocates an enumerator. Core and Controls: - BoxView's path is a rectangle when it has no corner radius. - ShapeDrawable draws a path that the shape can reuse while the bounds don't change (internal IShapeWithReusablePath, implemented by BoxView), unless it has a render transform to apply. Not on Windows, whose canvas keeps device-dependent geometry with the path. IShape.PathForBounds still returns a new path. - On Android, UpdateShape reuses the ShapeDrawable instead of creating a new one for every change of the shape. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…t paints like new TextPaint(Paint) - Subclasses of PlatformCanvas can reach the canvas states and their Java paints through CurrentState, for example to set a bitmap shader that a reused state would keep, so they keep getting new states, as they keep getting scaled copies of paths. - new TextPaint(Paint) leaves the fields that TextPaint adds at their defaults, but TextPaint.Set(TextPaint) copies them. A reused font paint is now reset from the default font paint before the source's Paint properties are copied into it. - Android device tests for PlatformCanvas: states are reused without allocating, reused states start from their prototype, changed paths are converted again, the fill type follows each fill, and ScalingCanvas clips to and fills scaled paths, passing scaled copies to subclasses. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
🟡 Changes recommended
Production owners do not dispose their PlatformCanvas instances, leaving newly cached native paths and pooled paints awaiting garbage collection instead of deterministic cleanup.
1 open issue
What changed in this PR
This PR reduces drawing allocations for Android BoxView and shapes in MAUI’s Graphics pipeline, complementing the related CollectionView scrolling optimizations. It reuses drawing resources without adding public APIs.
Changes:
- Pool Android canvas states and cache native path conversions, passing scale factors directly instead of creating scaled path copies.
- Cache eligible BoxView paths, simplify square-corner geometry, and reuse Android shape drawables while preserving subclass behavior.
- Add unit and device tests for reuse, invalidation, scaling, winding rules, and render-transform handling.
| File | Description |
|---|---|
src/Graphics/tests/DeviceTests/Tests/PlatformCanvasTests.Android.cs |
Tests state reuse, path invalidation, winding, scaling, and subclasses. |
src/Graphics/src/Graphics/ScalingCanvas.cs |
Delegates scaled paths to compatible canvases without copying. |
src/Graphics/src/Graphics/Platforms/Android/PlatformCanvasStateService.cs |
Pools released states and disposes pooled resources. |
src/Graphics/src/Graphics/Platforms/Android/PlatformCanvasState.cs |
Copies state into existing paints and clears pooled shaders. |
src/Graphics/src/Graphics/Platforms/Android/PlatformCanvas.cs |
Reuses states and native paths; accepts direct path scaling. |
src/Graphics/src/Graphics/Platforms/Android/GraphicsExtensions.cs |
Appends geometry to existing Android paths without enumerator allocation. |
src/Graphics/src/Graphics/PathF.cs |
Tracks invalidation versions for conversion caching. |
src/Graphics/src/Graphics/IScaledPathCanvas.cs |
Adds an internal contract for scaled path operations. |
src/Graphics/src/Graphics/CanvasState.cs |
Shares state-copy logic for in-place reuse. |
src/Graphics/src/Graphics/AbstractCanvas.cs |
Adds a state-release hook for pooling. |
src/Core/tests/UnitTests/ShapeDrawableTests.cs |
Tests reusable paths and render-transform isolation. |
src/Core/src/Platform/Android/ShapeViewExtensions.cs |
Resets and reuses compatible shape drawables. |
src/Core/src/Graphics/ShapeDrawable.cs |
Uses reusable paths where transforms and backend constraints permit. |
src/Core/src/Graphics/IShape.cs |
Defines the internal reusable-shape-path contract. |
src/Controls/tests/Core.UnitTests/BoxViewUnitTests.cs |
Tests geometry, cache invalidation, and subclass compatibility. |
src/Controls/src/Core/BoxView/BoxView.cs |
Caches drawing paths and simplifies square-corner rectangles. |
Review effort: Balanced
| _platformPathIsValid = false; | ||
| _platformPath?.Dispose(); | ||
| _platformPath = null; |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
| public override void Dispose() | ||
| { | ||
| _platformPathIsValid = false; | ||
| _platformPath?.Dispose(); |
There was a problem hiding this comment.
[moderate] Memory Leak Prevention - The cached native path and pooled paints are released only by PlatformCanvas.Dispose(), but PlatformGraphicsView never disposes its owned PlatformCanvas, and PlatformBitmapExportContext.Dispose() disposes only its Android canvas and bitmap. After drawing and disposing either owner, these newly retained native resources therefore await GC/finalization, or remain retained while the disposed owner is still referenced; converted paths were previously disposed after each operation. Wire disposal of the owned PlatformCanvas into both production owners. The new tests dispose PlatformCanvas directly and do not cover either ownership path.
| canvas.RestoreState(); | ||
|
|
||
| canvas.FillColor = Colors.Blue; | ||
| canvas.FillPath(path); |
There was a problem hiding this comment.
[moderate] Regression Prevention and Test Coverage - RestoreState resets the scale to (1,1) before this FillPath call, so the test never checks optimized FillPath with scaled geometry. The subclass test bypasses the optimization, and neither test calls DrawPath. Passing (1,1) instead of the requested scale in optimized FillPath would therefore leave these tests green despite incorrectly sized fills. Add fill and stroke assertions while a non-unit, unequal X/Y scale is active, plus unscaled control assertions. Unequal factors also distinguish the earlier Y-scale regression recorded in pinned history; both new fixtures currently use (2,2).
Selected Tests
🧪 Test selection — click to expand
🧪 UI tests —
|
| Platform | Categories |
|---|---|
| Android | Border, BoxView, Brush, GraphicsView, Shape |
| iOS | Border, BoxView, Brush, GraphicsView, Shape |
| MacCatalyst | Border, BoxView, Brush, GraphicsView, Shape |
| Windows | Border, BoxView, Brush, GraphicsView, Shape |
🧪 Device tests — Controls.Border, Controls.BoxView, Controls.Shape, Core.Border +5 on Android, iOS, MacCatalyst, Windows
❌ Could not queue maui-pr-devicetests: Azure Pipelines did not start maui-pr-devicetests for the dispatch branch run-devicetests/pr40902-46513601059 within 10 minutes. Comment /review run-tests again, or use /azp run maui-pr-devicetests for the full suite.
GPT-6.2 Sol: Run targeted Graphics and handler device tests for shared BoxView geometry and Android path and paint reuse.
MAI Code 2: Run BoxView, shape, and Graphics device tests on non-Windows platforms for reusable-path and Android canvas changes.
🧪 Running — 9 categories on Android, iOS, MacCatalyst, Windows
| Platform | Categories |
|---|---|
| Android | Controls.Border, Controls.BoxView, Controls.Shape, Core.Border, Core.BoxView, Core.Graphics, Core.GraphicsView, Core.ShapeView, Graphics |
| iOS | Controls.Border, Controls.BoxView, Controls.Shape, Core.Border, Core.BoxView, Core.Graphics, Core.GraphicsView, Core.ShapeView, Graphics |
| MacCatalyst | Controls.Border, Controls.BoxView, Controls.Shape, Core.Border, Core.BoxView, Core.Graphics, Core.GraphicsView, Core.ShapeView, Graphics |
| Windows | Controls.Border, Controls.BoxView, Controls.Shape, Core.Border, Core.Graphics, Core.GraphicsView, Core.ShapeView, Graphics |
⏭️ Skipped — what neither suite runs
UI tests — 72 categories, 0 platforms
Categories not run: Accessibility, ActionSheet, ActivityIndicator, Animation, AppLinks, Button, CarouselView, CollectionView1, CollectionView2, CollectionView3, CollectionView4, CollectionView5, CollectionView6, CollectionView7, Cells, CheckBox, ContextActions, CustomRenderers, DatePicker, Dispatcher, DisplayAlert, DisplayPrompt, DragAndDrop, Entry, Editor, Effects, Essentials, FlyoutPage, Focus, Fonts, Frame, Gestures, Image, ImageButton, IndicatorView, InputTransparent, IsEnabled, IsVisible, Label, Layout, Lifecycle, ManualReview, Maps, Navigation, Page, Performance, Picker, ProgressBar, RadioButton, RefreshView, SafeAreaEdges, Shadow, ScrollView, SearchBar, Slider, SoftInput, Stepper, Switch, SwipeView, Shell1, Shell2, TabbedPage, TableView, TimePicker, TitleView, ToolbarItem, Triggers, ViewBaseTests, VisualStateManager, Window, WebView, Material3
Each skipped platform and category is listed as a maui-pr-uitests (skipped) … status on this commit. Use /azp run maui-pr-uitests for the full suite.
Device tests — 96 categories, 0 platforms
Categories not run: Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Button, Controls.CarouselView, Controls.CheckBox, Controls.CollectionView, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml, Core.ActivityIndicator, Core.Animation, Core.Application, Core.Button, Core.CheckBox, Core.ContentView, Core.DatePicker, Core.Dispatcher, Core.Editor, Core.Element, Core.Entry, Core.FlowDirection, Core.FlyoutView, Core.Fonts, Core.Formatting, Core.Image, Core.ImageButton, Core.ImageSource, Core.IndicatorView, Core.Label, Core.Layout, Core.Lifecycle, Core.MauiContext, Core.Memory, Core.NavigationPage, Core.Page, Core.Picker, Core.ProgressBar, Core.RadioButton, Core.RefreshView, Core.ScrollView, Core.SearchBar, Core.Slider, Core.Stepper, Core.SwipeView, Core.Switch, Core.TimePicker, Core.View, Core.WebView, Core.Window, Core.WindowOverlay, Essentials, BlazorWebView
Each skipped platform and project is listed as a maui-pr-devicetests (skipped) … status on this commit. Use /azp run maui-pr-devicetests for the full suite.
🤖 Why these tests — AI rationale (GPT-6.2 Sol + MAI Code 2)
UI tests
Each model chose independently; every test that runs was selected by at least one of them.
| Platform | GPT-6.2 Sol | MAI Code 2 |
|---|---|---|
| Android | BoxView, Shape, GraphicsView, Border, Brush |
BoxView, Shape, GraphicsView |
| iOS | BoxView, Shape, GraphicsView, Border, Brush |
BoxView, Shape, GraphicsView |
| MacCatalyst | BoxView, Shape, GraphicsView, Border, Brush |
BoxView, Shape, GraphicsView |
| Windows | BoxView, Shape, GraphicsView, Border, Brush |
— |
GPT-6.2 Sol — Run targeted rendering UI tests for shared BoxView geometry and Android canvas, shape, and clipping changes.
- Shared BoxView geometry affects all four platforms.
- Android canvas reuse touches Shape and GraphicsView; path conversion touches Border clips and paint reuse touches Brush fills.
- No item-handler or layout changes; skip CollectionView shards and full run.
MAI Code 2 — Reusable BoxView/shape paths and Android canvas optimizations; run BoxView, Shape, and GraphicsView UI coverage on Android, iOS, and Mac Catalyst.
BoxView.csnow reuses rounded-rectangle paths andShapeDrawableconsumes reusable paths on all non-Windows platforms, so BoxView and Shape coverage must run on Android, iOS, and Mac Catalyst.- Android
PlatformCanvasnow reuses native Paint/Path objects and canvas states; GraphicsView coverage validates direct ICanvas fill, clip, gradient, shadow, and scaling behavior there. - Windows is excluded because reusable-path drawing is explicitly compiled out and the BoxView geometry remains equivalent; unrelated control categories are deliberately omitted.
Device tests
Each model chose independently; every test that runs was selected by at least one of them.
| Platform | GPT-6.2 Sol | MAI Code 2 |
|---|---|---|
| Android | Graphics, Controls.BoxView, Controls.Shape, Core.ShapeView, Core.Graphics, Core.GraphicsView, Controls.Border, Core.Border |
Controls.BoxView, Controls.Shape, Core.BoxView, Core.ShapeView, Graphics |
| iOS | Graphics, Controls.BoxView, Controls.Shape, Core.ShapeView, Core.Graphics, Core.GraphicsView, Controls.Border, Core.Border |
Controls.BoxView, Controls.Shape, Core.BoxView, Core.ShapeView, Graphics |
| MacCatalyst | Graphics, Controls.BoxView, Controls.Shape, Core.ShapeView, Core.Graphics, Core.GraphicsView, Controls.Border, Core.Border |
Controls.BoxView, Controls.Shape, Core.BoxView, Core.ShapeView, Graphics |
| Windows | Graphics, Controls.BoxView, Controls.Shape, Core.ShapeView, Core.Graphics, Core.GraphicsView, Controls.Border, Core.Border |
— |
GPT-6.2 Sol — Run targeted Graphics and handler device tests for shared BoxView geometry and Android path and paint reuse.
- Shared BoxView geometry needs all four platforms.
- Graphics and Core.Graphics cover Android canvas state and paths.
- Shape and GraphicsView exercise redraws; Border uses the changed clip conversion.
- No startup, layout, or build changes requiring a full run.
MAI Code 2 — Run BoxView, shape, and Graphics device tests on non-Windows platforms for reusable-path and Android canvas changes.
- Shared
BoxViewandShapeDrawablechanges requireControls.BoxView,Controls.Shape,Core.BoxView, andCore.ShapeViewcoverage on non-Windows platforms, matching the changed drawing path. - Android-specific
PlatformCanvasand state/path reuse changes, plus a new Android Graphics device-test file, require theGraphicsunit on Android; the selected non-Windows platform scope also covers shared Graphics abstractions used by the change. - Windows is excluded because reusable-path drawing is disabled there, and no lifecycle, app-startup, or shared test-infrastructure changes warrant a full device run.
Generated by /review run-tests. A targeted run is a fast signal, not full-suite certification.
…ld (#40942) <!-- copilot-assessment:v1 --> ### Agent assessment Self-reported assessment, not an independent review. Assessed revision: `d4994306f4a22c3573e3d945ef4e39dca26cd6f2` | Dimension | Assessment | Rationale | |---|---|---| | Change confidence | 9/10 | ↑ A minimal repro of the old pattern with `WINDOWS` defined raises the same CA1822 error; the new pattern is clean with and without `WINDOWS`.<br>↑ `ShapeDrawableTests` pass (2/2) and Core unit tests build with `-warnaserror` on `net12.0`.<br>↑ Behavior is unchanged: Windows already always used `PathForBounds`.<br>↓ The real `net12.0-windows10.0.19041.0` build couldn't complete on macOS (the WinUI XAML compiler and MakePri only run on Windows); CI is pending. | | Diagnosis confidence | 10/10 | ↑ The error points at `GetPath`, whose only instance access (`RenderTransform`) is inside `#if !WINDOWS`, added in #40902. | | Evidence fit | 9.5/10 | ↑ The official build log reports exactly `ShapeDrawable.cs(73,10): error CA1822` for `GetPath`, starting with the first build that contains #40902. | <!-- /copilot-assessment --> <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change The official build (`dotnet-maui`, dnceng/internal) fails on `main` in Pack Windows since build 3149608: ``` src/Core/src/Graphics/ShapeDrawable.cs(73,10): error CA1822: Member 'GetPath' does not access instance data and can be marked as static ``` #40902 added `ShapeDrawable.GetPath`, whose only instance access (`RenderTransform`) is inside `#if !WINDOWS`. On the Windows TFMs the method therefore uses no instance data, and the Release build runs with `-warnAsError`. Fix: declare a `static` `GetPath` that returns `shape.PathForBounds(bounds)` on Windows, and keep the instance method for other platforms. Behavior doesn't change on any platform. The other shared files touched by #40902 have no TFM-conditional code, so they aren't affected. Validation: - Minimal repro of the old and new patterns with CA1822 enabled: the old pattern with `WINDOWS` defined fails with CA1822; the new one builds without errors with and without `WINDOWS`. - `dotnet build src/Core/tests/UnitTests/Core.UnitTests.csproj -warnaserror`: succeeded. `Microsoft.Maui.UnitTests --filter-class Microsoft.Maui.UnitTests.ShapeDrawableTests`: 2 passed, 0 failed. - `dotnet format whitespace --folder --include src/Core/src/Graphics/ShapeDrawable.cs --verify-no-changes`: no changes. - Not run: `dotnet build src/Core/src/Core.csproj -c Release -f net12.0-windows10.0.19041.0 -warnaserror` on macOS stops at the WinUI XAML compiler (Windows-only) after restore; CI covers the Windows build. ### Issues Fixed Part of #40940 (F2). ### Let AI finish this PR - [x] **Let the MAUI agent address review feedback and fix remaining issues on this PR.** Maintainers still decide whether it is merged. For PRs from forks, keep "Allow edits by maintainers" on so the agent can push to your branch; otherwise it opens a follow-up PR that keeps your commits. <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>

Agent assessment
Self-reported assessment, not an independent review.
Assessed revision:
584853032461f4bf7d3983bf37be87fb4cdb1955↑ Android screenshots of the benchmark are pixel-identical to
main.↑ Graphics device tests pass on Android 15 (39/39, including 6 new ones); Core unit tests pass (1,411/1,411).
↑ Controls unit tests all pass (7,909) with the leak-test fixes that
mainhas since made (#40882).↑ An independent review found two issues; both are fixed and the re-review was clean.
↓ The CPU and rebind-time gains aren't significant on the emulator.
↓ Not built or run on Windows or run on iOS; Mac Catalyst rendering wasn't checked visually.
↓ Controls device tests and UI tests weren't run locally; CI is pending.
↓ Each Android canvas keeps up to 4 pooled states with 3 Java paints each.
Note
Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!
Target Branch
mainnet11, for reviewFor .NET 11 fixes, only a maintainer retargets the approved PR to the active
inflight lane and merges it after CI validates that final base. Do not merge
individual fixes directly into
net11; agents must not retarget or merge.Description of Change
On Android, every draw of a
BoxViewor another shape created about 21 JavaPaints, 2 JavaPaths and 3PathFs. A shape's view (MauiShapeView) is aPlatformGraphicsView, which draws aShapeDrawablethrough aScalingCanvasaround the AndroidPlatformCanvas:Canvasbefore and after drawing, and resets theScalingCanvas. Each reset disposed the state and created a new one with three new paints, andPlatformCanvas.ResetStatethen replaced those with three more copies of the same defaults.ShapeDrawable'sSaveStatecreated one more state.ShapeDrawableclips to the shape's path and fills it. For each,ScalingCanvascreated a scaled copy of thePathF, andPlatformCanvasconverted the copy into a new AndroidPath.PathForBoundsbuilt a new rounded-rectangle path for every draw, with zero-radius curves when there are no rounded corners.A
CollectionViewredraws a row'sBoxViewwhenever the row is rebound with a different color. In the CollectionView scroll benchmark (on a branch for reference; not part of this PR), drawing it took 13% of the UI thread's CPU samples and about 20% of its allocations. #40881 listsShapeDrawableamong the allocations it leaves.Changes
Microsoft.Maui.Graphics on Android
PlatformCanvasreuses canvas states.AbstractCanvasnow releases the states it no longer uses through a newprivate protected virtual ReleaseState, which by default disposes them, as before.PlatformCanvasreturns them to itsPlatformCanvasStateService. The service keeps up to 4, and makes a released state a copy of the default or saved state by copying paints withPaint.Setinstead of creating new ones. OnlyPlatformCanvasitself reuses states: subclasses can reach the states' paints throughCurrentState, so they still get new states.PlatformCanvas.ResetStateno longer replaces the paints of the state it has just created with new copies of the same defaults.PlatformCanvasconverts the paths it draws, fills or clips to into one AndroidPaththat it reuses. It converts again only for a different path, a changed path or a different scale. To detect changes,PathFgets an internal version thatInvalidate()increments; all ofPathF's mutators call it.ScalingCanvaspasses its scale toPlatformCanvas(through the internalIScaledPathCanvas) instead of creating scaled copies of paths. Other canvases andPlatformCanvassubclasses still get scaled copies.AsAndroidPathno longer allocates an enumerator.Core and Controls
BoxViewwithout rounded corners has a rectangle path.ShapeDrawabledraws a path that the shape can reuse while its bounds don't change. This is the internalIShapeWithReusablePath, whichBoxViewimplements by caching its path for the bounds and corner radius.ShapeDrawabledoesn't use it when it has a render transform to apply to the path, or on Windows, whose canvas keeps device-dependent geometry with the path.IShape.PathForBoundsstill returns a new path every time.UpdateShapereuses the view'sShapeDrawable, reset to how a new one starts, instead of creating a new one for every change of the shape.There are no public API changes.
Why it's safe
new TextPaint(Paint)copies them, which leaves the fields thatTextPaintadds at their defaults.Pathdoesn't change what was drawn before. The conversion is keyed by a weak reference to thePathF, its version and the scale; a conversion that throws is done again.AsScaledPath's copy.BoxViewpath:ShapeDrawableonly clips to it, fills it and strokes it. On iOS and Mac Catalyst, the canvas now also reuses theCGPaththat it caches on the path.PlatformCanvassubclasses andBoxViewsubclasses, which can reimplementIShape.PathForBounds, keep the previous behavior.Behavior changes
main, both before and after scrolling.PlatformCanvaskeeps up to 4 released states, with 3 Java paints each, and one AndroidPathuntil it's disposed. ABoxView's canvas keeps one state more than before. In exchange, drawing no longer creates Java objects.Measurements
The benchmark scrolls a
CollectionViewof 1,000 items by 100 dp per frame, for 240 frames per pass. Its row template is aGridwith aBoxViewwhoseColoris bound, 7Labels, aProgressBarand aCheckBox. Each launch runs a cold pass, a warm-up pass and 5 warm passes; a pass binds 267 rows.Setup: Android 15 emulator (
sdk_gphone64_arm64, Pixel 6 profile, 4 cores, 4 GB) on an Apple silicon Mac; Release; CoreCLR .NET 12.0.0-alpha.1.26523.103 (SDK 12.0.100-alpha.1.26523.103).mainbd40bc6 against 5a4448b, the first commit of this PR, in 10 interleaved launch pairs. Values are medians over the launches of each launch's warm-pass median, with the median paired difference and its 95% sign-test interval:mainmainand of the final commit):PlatformGraphicsView.Drawdropped from 187 to 35 UI-thread samples (13.0% → 3.0%), and from 20.1% to 0.6% of the UI thread's sampled allocations. Within it,AbstractCanvas.ResetStatedropped from 66 samples to 2,Paintconstructors from 42 to 0, andAsAndroidPathfrom 28 to 0.Tests
New tests:
BoxViewUnitTests(Controls): the path without rounded corners is a rectangle; one rounded corner gives a rounded path; the reusable path is kept until the bounds or the corner radius change; a subclass'sPathForBoundsis used.ShapeDrawableTests(Core): the shape's reusable path is drawn; a render transform isn't applied to it.PlatformCanvasTests(Graphics device tests, Android): saving, restoring and resetting states doesn't allocate; reused states start from their prototype (color, alpha, gradient shader and shadow don't carry over); a changed path is converted again; the winding mode follows each fill;ScalingCanvasclips to and fills scaled paths, and passes scaled copies to subclasses.Commands, with
.dotnetlinked to the SDK fromglobal.json:.dotnet/dotnet build src/Core/tests/UnitTests/Core.UnitTests.csproj, thenartifacts/bin/Core.UnitTests/Debug/net12.0/Microsoft.Maui.UnitTests: 1,411 passed, 0 failed..dotnet/dotnet build src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj, thenartifacts/bin/Controls.Core.UnitTests/Debug/net12.0/Microsoft.Maui.Controls.Core.UnitTests: 7,878 passed, 30 skipped, 31 failed. The 31 are GC leak tests (tests named*DoesNotLeak*,CommandsSubscribedToCanExecuteCollectand threeTransformGroupTests). The same 31 fail onmainbd40bc6's sources, where 7,874 pass without the 4 new tests, and Fix Controls.Core.UnitTests leak tests under runtime async #40882 has since fixed them onmain. With Fix Controls.Core.UnitTests leak tests under runtime async #40882's test changes applied to this branch: 7,909 passed, 30 skipped, 0 failed.pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Graphics -Platform android -DeviceUdid emulator-5600 -DotnetPath .dotnet/dotnet: 39 passed, 0 failed, on the Android 15 emulator, including the 6 new tests..dotnet/dotnet format whitespace --folder --include <changed files> --verify-no-changes: no changes.net12.0,net12.0-android37.0,net12.0-ios27.1andnet12.0-maccatalyst27.0; Core and Controls fornet12.0andnet12.0-android37.0; and Release builds of the benchmark for Android and Mac Catalyst, which validate the PublicAPI files.Build-ScrollBenchmark.ps1 -Variant fix -Platform android -MauiRoot <this checkout>,Invoke-ScrollBenchmark.ps1 -Variants base,fix -Platform android -Rounds 10 -Serial emulator-5600andCompare-ScrollBenchmark.ps1 <results>.jsonl -Baseline base -Candidate fix.Not run:
net12.0, Windows-specific code is unchanged, andShapeDrawabledoesn't reuse paths on Windows.BoxViewTests,ShapeTests), UI tests, physical Android devices and other Android API levels.Issues Fixed
No issue filed; this is a performance improvement. Related: #40881 (fewer temporary allocations while scrolling a
CollectionViewon Android; no files in common), and #39909 and #39914 (deterministic disposal of Android Graphics objects, which this keeps).Let AI finish this PR