Repository navigation
[net12] Add support for background images with ImageBrush - #36329
HarishwaranVijayakumar wants to merge 18 commits into
Conversation
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 36329Or
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 36329" |
|
Hey there @@HarishwaranVijayakumar! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed. |
|
/azp run |
|
Azure Pipelines successfully started running 3 pipeline(s). |
This comment has been minimized.
This comment has been minimized.
kubaflo
left a comment
There was a problem hiding this comment.
Could you please check the ai's suggestions?
This comment has been minimized.
This comment has been minimized.
MauiBot
left a comment
There was a problem hiding this comment.
Expert Review — 8 findings
See inline comments for details.
|
|
||
| Drawable[] layers = [imageDrawable, strokeDrawable]; | ||
| var layerDrawable = new LayerDrawable(layers); | ||
| layerDrawable.SetId(0, MauiBackgroundDrawableId); |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[major] Handler Mapper and Property Patterns / Logic and Correctness — UpdateMauiRippleDrawableImageBackground (new in this PR) stores the loaded imageDrawable under MauiBackgroundDrawableId inside the LayerDrawable. But TryGetMauiBackground (same file, line 241) only recognizes a MAUI background when layerDrawable.FindDrawableByLayerId(MauiBackgroundDrawableId) is GradientDrawable — an arbitrary loaded image Drawable (typically a BitmapDrawable) never satisfies that cast. Concrete repro: set Button.Background/ImageButton.Background to an ImageSourcePaint, then change StrokeColor, StrokeThickness, or CornerRadius. UpdateButtonStroke (ButtonExtensions.cs:45-60, unchanged by this PR) calls UpdateMauiRippleDrawableStroke → TryGetMauiBackground, which now always returns false for an image background, so the code silently falls back to setting platformView.StrokeColor/StrokeWidth/CornerRadius directly on the native MaterialButton/ShapeableImageView — properties with no visual effect because Background is now the custom RippleDrawable built by this method. Net effect: stroke/corner-radius changes are silently ignored for any Button/ImageButton with an image background.
|
|
||
| if (background is ImageSourcePaint sourcePaint) | ||
| { | ||
| platformView.UpdateBackgroundImageSource(sourcePaint.ImageSource, view.Handler); |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[major] Logic and Correctness / Regression Prevention — When view.Background is an ImageSourcePaint, this new branch routes to UpdateBackgroundImageSource, whose async completion (UpdateBackgroundImageSourceAsync, line 498, unchanged) assigns the loaded image as a raw Drawable directly to platformView.Background — not wrapped in a MauiDrawable/MauiLayerDrawable. When the background later changes away from the image (e.g., back to null), the else branch calls UpdateBackground(background, treatTransparentAsNull) (line 335), which only clears backgrounds it recognizes as MauiDrawable (line 342) or, for empty paint, only for platformView is LayoutViewGroup or ContentViewGroup (line 366). A plain TextView-based control (e.g., Label, whose LabelHandler.Android.cs MapBackground calls this exact path) is neither, so setting Label.Background = ImageSourcePaint(...) then Label.Background = null leaves the stale image drawable visibly persisting on the label. Switching to a SolidPaint/GradientPaint does work (those branches unconditionally overwrite platformView.Background), so only the null/empty-paint case is broken.
| if (platformView is Control control) | ||
| { | ||
| control.Resources.SetValueForAllKey(resourceKeys, imageBrush); | ||
| control.Background = imageBrush; |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[major] Logic and Correctness / Cross-Platform Consistency — UpdateBackgroundImageForAllStatesAsync (new in this PR) sets control.Background = imageBrush; as a direct local value, in addition to the Resources dictionary entries used for the PointerOver/Pressed/Disabled visual states. None of its callers (ButtonExtensions.UpdateBackground, DatePickerExtensions.UpdateBackground, PickerExtensions.UpdateBackground, TextBoxExtensions.UpdateBackground, TimePickerExtensions.UpdateBackground, RadioButtonExtensions.UpdateBackground, SliderExtensions.UpdateBackgroundColor, SearchBarExtensions.UpdateBackground — all modified in this PR) ever reset control.Background back to null/default when the paint later becomes null or a SolidPaint; they only call Resources.RemoveKeys(...)/SetValueForAllKey(...). Because a directly-assigned local value on a DependencyProperty takes precedence over template/VisualState ThemeResource Setters, the control's Normal visual state keeps showing the stale image after the background is changed away from an ImageSourcePaint, even though hover/pressed/disabled states correctly revert via the resource keys. Concrete repro: set Button.Background to an ImageSource, then set it back to null — the button keeps rendering the old image in its Normal state.
|
|
||
| if (background is ImageSourcePaint sourcePaint) | ||
| { | ||
| layoutPanel?.UpdateBackgroundImageSource(sourcePaint.ImageSource, layout.Handler); |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[major] Layout Measure-Arrange Correctness / Logic and Correctness — UpdatePlatformViewBackground(this LayoutPanel layoutPanel, ILayout layout) has a doc comment directly above (lines 362-365) stating "Background and InputTransparent for Windows layouts are heavily intertwined, so setting one usually requires setting the other at the same time." The new ImageSourcePaint branch (added in this PR) calls layoutPanel?.UpdateBackgroundImageSource(...) directly, completely bypassing UpdateInputTransparent(layout.InputTransparent, ...) that the else branch still calls. Concrete repro: a Layout (e.g. Grid/VerticalStackLayout) with InputTransparent=true and an ImageSourcePaint background will not get the input-transparency handling applied, so it can become hit-testable and block touch/pointer input to elements beneath it, unlike the same layout with any other background type.
| { | ||
| [ContentProperty(nameof(ImageSource))] | ||
| class ImageBrush : Brush | ||
| public class ImageBrush : Brush |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[moderate] Public API Surface Design / Logic and Correctness — This line makes ImageBrush public (previously internal), and the accompanying PublicAPI.Unshipped.txt entries in this PR ship Equals/GetHashCode as public API. Equals (line 28-29) performs value comparison on ImageSource, while GetHashCode() (line 31) returns base.GetHashCode() — reference-identity, since neither Brush nor Element overrides it. This violates the .NET contract that equal objects must produce equal hash codes: two distinct ImageBrush instances referencing the same ImageSource compare Equal but hash differently, breaking correctness for Dictionary<ImageBrush,_>/HashSet<ImageBrush> usage. Since this is now public/shipped API, the defect can no longer be fixed without a breaking change.
| break; | ||
|
|
||
| case ImageSourcePaint image: | ||
| uiSearchBar.UpdateBackgroundImageSource(image.ImageSource, searchBar.Handler); |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[moderate] Cross-Platform Behavioral Consistency / Logic and Correctness — The new case ImageSourcePaint image: branch only calls UpdateBackgroundImageSource, unlike the sibling null (line 42-43) and SolidPaint (line 51 onward) branches, which both explicitly reset BarTintColor (to UISearchBar.Appearance.BarTintColor or the solid color, respectively). Concrete repro: set SearchBar.Background to a SolidPaint (setting BarTintColor to that color), then change it to an ImageSourcePaint. BarTintColor is never reset, so the previously-applied opaque tint color remains active on the search bar chrome and can visually obscure the newly set background image layer, which is inserted underneath via InsertBackgroundLayer(imageLayer, 0).
| } | ||
| //If this is a Mac optimized interface | ||
| if (OperatingSystem.IsIOSVersionAtLeast(15) && UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Mac) | ||
| else if (OperatingSystem.IsIOSVersionAtLeast(15) && UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Mac) |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[major] Cross-Platform Behavioral Consistency / Regression Prevention — On MacCatalyst, the pre-existing if at this line was changed to else if, making it mutually exclusive with the new ImageSourcePaint branch above (lines 54-57). When running on Mac idiom + iOS 15+, switching Button.Background from an ImageSourcePaint to a SolidPaint/other paint takes this else if branch, which only sets UIButtonConfiguration.BaseBackgroundColor — it never calls RemoveBackgroundLayer() (unlike the non-Mac-idiom else branch at line 80, which reaches UpdateBackground(Paint?, ...) → RemoveBackgroundLayer() in ViewExtensions.cs). The custom background image CALayer previously inserted via UpdateBackgroundImageSource/InsertBackgroundLayer is never removed, so the stale image remains visible underneath/alongside the new configuration-based background on Mac-idiom Catalyst apps.
| return; | ||
| } | ||
|
|
||
| platformView.UpdateMauiRippleDrawableImageBackground(backgroundImageDrawable, stroke, getDefaultRippleColor, beforeSet); |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[moderate] Async and Threading Safety — UpdateButtonBackgroundImageSourceAsync (new in this PR, plus the sibling UpdateBorderImageBackgroundAsync/UpdateBackgroundImageSourceAsync additions in this file and the iOS/Windows equivalents) is fire-and-forget with no staleness/generation check: once the async image load completes, it unconditionally calls UpdateMauiRippleDrawableImageBackground/assigns the platform background, without verifying the requested imageSource is still the one currently desired on VirtualView. Rapidly toggling Background between two different ImageSourcePaints, or from an image to a solid color/null and back, can let a stale, out-of-order completion overwrite an already-applied newer background, leaving the wrong image/color visible.
|
/azp run maui-pr-uitests |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
This comment has been minimized.
This comment has been minimized.
8aca808 to
3b8027b
Compare
This comment has been minimized.
This comment has been minimized.
MauiBot
left a comment
There was a problem hiding this comment.
Expert Review — 14 findings
See inline comments for details.
| ctx.SaveState(); | ||
| ctx.TranslateCTM(0, _bounds.Height); | ||
| ctx.ScaleCTM(1, -1); | ||
| ctx.DrawImage(new CGRect(0, 0, _bounds.Width, _bounds.Height), _backgroundImage.CGImage); |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[major] Layout / Cross-Platform Consistency — The background image is drawn without applying the layer's clip path, unlike the _backgroundColor branch below (line 356) which calls GetClipPath() and ctx.AddPath(clipPath) before filling. MauiCALayer is the backing layer for Border/IBorderStroke views, so its shape comes from _shape. Concrete scenario: <Border StrokeShape="RoundRectangle 20"><Border.Background><ImageBrush ImageSource="dotnet_bot.png"/></Border.Background></Border> renders the image as a full square that spills outside the rounded corners, while the stroke is drawn as a rounded rect on top. Wrap the DrawImage call in ctx.AddPath(GetClipPath()); ctx.Clip(); (inside the existing Save/Restore) so the image respects the shape.
| var rippleColor = getDefaultRippleColor?.Invoke() | ||
| ?? ColorStateList.ValueOf(Colors.White.WithAlpha(DefaultRippleAlpha).ToPlatform()); | ||
|
|
||
| Drawable[] layers = [imageDrawable, strokeDrawable]; |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[major] Cross-Platform Consistency — imageDrawable is inserted as layer 0 of the LayerDrawable with no corner-radius clipping. strokeDrawable only paints the stroke ring and maskDrawable only bounds the ripple, so nothing clips the image itself. In the non-image path the background layer is a GradientDrawable/MauiDrawable that has SetCornerRadius(radius) applied, so it is clipped. Concrete scenario: a Button with CornerRadius="20" and an ImageBrush background shows square image corners protruding past the rounded stroke. Same defect exists in ViewExtensions.UpdateBorderImageBackgroundAsync (Android) for Border. Consider wrapping the image in a RoundedBitmapDrawable/ShapeDrawable mask or drawing it through MauiDrawable.
| platformView.Background = null; | ||
| previousDrawable.Dispose(); | ||
| previousDrawable = null; | ||
| ((AView)platformView).UpdateBackgroundImageSource(sourcePaint.ImageSource, view.Handler); |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[major] Logic and Correctness — Routing the ImageSourcePaint case to UpdateBackgroundImageSource bypasses the entire EditText background contract implemented in the else branch below: (1) the AndroidX abc_edit_text_material underline drawable is never re-applied, so an Entry/Editor with an ImageBrush background loses its Material "line"; (2) more importantly, UpdateBackgroundImageSourceAsync assigns platformView.Background = drawable directly, and Android resets a view's padding whenever Background is set. The local SetBackground helper (line ~318) exists specifically to cache and re-apply PaddingLeft/Top/Right/Bottom — the image path skips it, so the Entry's padding is silently zeroed the first time an ImageBrush background is applied.
|
|
||
| if (background is ImageSourcePaint sourcePaint) | ||
| { | ||
| platformView.UpdateBackgroundImageSource(sourcePaint.ImageSource, view.Handler); |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[major] Async and Threading Safety — UpdateBackgroundImageSource fires an un-cancellable FireAndForget image load, and the continuation (line ~499) assigns platformView.Background = backgroundImageDrawable without re-checking that the view's current background is still this ImageSourcePaint. Concrete scenario: view.Background = new ImageBrush(<slow/remote source>) followed immediately by view.Background = Brush.Red — the solid red drawable is applied synchronously, then the late image load completes and overwrites it, leaving the wrong background permanently. The same race exists for two ImageBrush assignments in quick succession (out-of-order completion wins). Capture a token/snapshot of the requested IImageSource before the await and bail out if view.Background no longer matches.
| else | ||
| { | ||
| // Remove LayerDrawable wrapper if switching away from image | ||
| if (platformView.Background is LayerDrawable) |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[major] Logic and Correctness — The "switching away from image" guard only unwraps the LayerDrawable if it has already been installed. Because the image path (line 158) installs the LayerDrawable asynchronously, a synchronous switch back to a solid/gradient paint while the image load is still in flight sees platformView.Background as the plain MauiDrawable, skips the unwrap, sets the solid background — and then the in-flight UpdateBorderImageBackgroundAsync completes and re-wraps the view in the image LayerDrawable, restoring the stale image over the new solid background. The unwrap check needs to be paired with cancellation/staleness detection on the async load, not just an instance-type test.
| var service = provider.GetRequiredImageSourceService(imageSource); | ||
| var result = await service.GetImageSourceAsync(imageSource); | ||
| var imageBrush = new WImageBrush { ImageSource = result?.Value }; | ||
| platformStepper.ButtonBackground = imageBrush; |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[moderate] Async and Threading Safety — platformStepper.ButtonBackground is assigned after the await with no aliveness or staleness check. If the handler was disconnected (or Background was changed to a solid paint) while GetImageSourceAsync was in flight, this writes to a disposed/re-purposed platform view. Also, when result?.Value is null the code still creates a WImageBrush with a null ImageSource, which paints the stepper buttons transparent rather than falling back to the previous/default button background.
| if (view.Background is ImageSourcePaint sourcePaint) | ||
| { | ||
| mauiCALayer.SetBackground(new SolidPaint(Colors.Transparent)); | ||
| platformView.UpdateBorderImageBackground(sourcePaint.ImageSource, view.Handler, mauiCALayer); |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[moderate] Logic and Correctness — mauiCALayer.SetBackground(new SolidPaint(Colors.Transparent)) is called synchronously and the image is applied later by UpdateBorderImageBackground. If the image service returns null (missing resource, failed URI load), UpdateBorderImageBackgroundAsync returns without calling SetBackgroundImage, so the border is left permanently transparent with no fallback. In addition, the same in-flight ordering race as Android applies: switching back to a solid paint before the load completes runs the else branch (SetBackgroundImage(null) + SetBackground), then the pending async completes and re-applies the stale image.
|
|
||
| internal void SetBackgroundImage(UIImage? image) | ||
| { | ||
| _backgroundImage = image; |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[moderate] Memory Leak Prevention — _backgroundImage holds a strong reference to a UIImage (and transitively its CGImage backing store) for the lifetime of the layer, and it is never released — there is no Dispose/cleanup that nulls it, and SetBackground(SolidPaint)/SetBackground(GradientPaint) do not clear it either (only the new else branch in StrokeExtensions.iOS calls SetBackgroundImage(null) explicitly). Any other code path that switches a MauiCALayer from an image background to a paint background will both leak the image and keep rendering it, because DrawBackground checks _backgroundImage first.
| { | ||
| [ContentProperty(nameof(ImageSource))] | ||
| class ImageBrush : Brush | ||
| public class ImageBrush : Brush |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[moderate] Public API Surface — Promoting ImageBrush from internal to public is a permanent API commitment and the shape should be reviewed deliberately: the class is unsealed while overriding Equals/GetHashCode (derived types will inherit equality that does not account for their own state — see the recent Color equality regression for the same pattern), and ImageSource is exposed as virtual, which locks in an extensibility point. Also note there is no Brush.Image(...)-style static factory or documentation added alongside, unlike the other public Brush subclasses. Consider sealed unless subclassing is an intended scenario.
| @@ -0,0 +1,134 @@ | |||
| using NUnit.Framework; | |||
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[moderate] Regression Prevention — Coverage is snapshot-only for the "apply an ImageBrush" case. The most fragile behavior introduced by this PR is the transition path: ImageBrush → SolidColorBrush/null and ImageBrush → different ImageBrush, which on every platform depends on an un-cancelled FireAndForget load completing before the next assignment (see findings in ViewExtensions.cs, StrokeExtensions.cs, RadioButtonExtensions.cs). Please add device/UI tests that (a) set an ImageBrush background, then set a solid background, and assert the solid color wins, and (b) exercise an ImageBrush whose ImageSource fails to resolve, asserting a sensible fallback rather than a permanently transparent control.
MauiBot
left a comment
There was a problem hiding this comment.
AI Review Summary
@HarishwaranVijayakumar — new AI review results are available based on commit
760bed1.
🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix
Gate Result: ✅ PASSED
Platform: IOS · Base: net11.0 · Merge base: 6801352a
| Test | Without Fix (expect FAIL) | With Fix (expect PASS) |
|---|---|---|
🖥️ Issue12928 Issue12928 |
✅ FAIL — 241s | ✅ PASS — 213s |
🔴 Without fix — 🖥️ Issue12928: FAIL ✅ · 241s
Error-relevant lines (filtered from the build log):
at VisualTestUtils.VisualRegressionTester.Fail(String message) in /_/src/TestUtils/src/VisualTestUtils/VisualRegressionTester.cs:line 162
at VisualTestUtils.VisualRegressionTester.VerifyMatchesSnapshot(String name, ImageSnapshot actualImage, String environmentName, ITestContext testContext) in /_/src/TestUtils/src/VisualTestUtils/VisualRegressionTester.cs:line 123
at Microsoft.Maui.TestCases.Tests.UITest.<VerifyScreenshot>g__Verify|13_0(String name, <>c__DisplayClass13_0&) in /_/src/Controls/tests/TestCases.Shared.Tests/UITest.cs:line 485
at Microsoft.Maui.TestCases.Tests.UITest.VerifyScreenshot(String name, Nullable`1 retryDelay, Nullable`1 retryTimeout, Int32 cropLeft, Int32 cropRight, Int32 cropTop, Int32 cropBottom, Double tolerance) in /_/src/Controls/tests/TestCases.Shared.Tests/UITest.cs:line 309
at Microsoft.Maui.TestCases.Tests.Issues.Issue12928.ImageBrushOnLabelAndButton() in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue12928.cs:line 20
at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
at Microsoft.Maui.TestCases.Tests.Issues.Issue12928.ImageBrushOnCheckBoxAndRadioButton() in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue12928.cs:line 68
at System.RuntimeMethodHandle.InvokeMethod(ObjectHandleOnStack target, Void** arguments, ObjectHandleOnStack sig, BOOL isConstructor, ObjectHandleOnStack result)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Maui.TestCases.Tests.Issues.Issue12928.ImageBrushOnContentViewAndBorder() in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue12928.cs:line 84
at Microsoft.Maui.TestCases.Tests.Issues.Issue12928.ImageBrushOnCollectionViewAndSwipeView() in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue12928.cs:line 92
at Microsoft.Maui.TestCases.Tests.Issues.Issue12928.ImageBrushOnGridAndFlexLayout() in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue12928.cs:line 108
at Microsoft.Maui.TestCases.Tests.Issues.Issue12928.ImageBrushOnAbsoluteLayoutAndScrollView() in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue12928.cs:line 116
at Microsoft.Maui.TestCases.Tests.Issues.Issue12928.ImageBrushOnCarouselViewAndStackLayout() in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue12928.cs:line 100
🟢 With fix — 🖥️ Issue12928: PASS ✅ · 213s
(no coded error found; showing last 1200 chars)
5/2026 3:41:24 PM ImageBrushOnContentViewAndBorder Stop
Passed ImageBrushOnContentViewAndBorder [6 s]
>>>>> 8/15/2026 3:41:24 PM ImageBrushOnCollectionViewAndSwipeView Start
>>>>> 8/15/2026 3:41:30 PM ImageBrushOnCollectionViewAndSwipeView Stop
Passed ImageBrushOnCollectionViewAndSwipeView [6 s]
>>>>> 8/15/2026 3:41:30 PM ImageBrushOnGridAndFlexLayout Start
>>>>> 8/15/2026 3:41:38 PM ImageBrushOnGridAndFlexLayout Stop
Passed ImageBrushOnGridAndFlexLayout [7 s]
>>>>> 8/15/2026 3:41:38 PM ImageBrushOnAbsoluteLayoutAndScrollView Start
>>>>> 8/15/2026 3:41:45 PM ImageBrushOnAbsoluteLayoutAndScrollView Stop
Passed ImageBrushOnAbsoluteLayoutAndScrollView [7 s]
>>>>> 8/15/2026 3:41:45 PM ImageBrushOnCarouselViewAndStackLayout Start
>>>>> 8/15/2026 3:41:53 PM ImageBrushOnCarouselViewAndStackLayout Stop
Passed ImageBrushOnCarouselViewAndStackLayout [7 s]
NUnit Adapter 4.5.0.0: Test execution complete
Results File: /Users/cloudtest/vss/_work/1/s/CustomAgentLogsTmp/UITests/TestResults/Issue12928.trx
Test Run Successful.
Total tests: 13
Passed: 13
Total time: 2.0061 Minutes
>>> TRX_RESULT_FILE: /Users/cloudtest/vss/_work/1/s/CustomAgentLogsTmp/UITests/TestResults/Issue12928.trx
📁 Fix files reverted (30 files)
src/Controls/src/Core/ImageBrush.cssrc/Controls/src/Core/PublicAPI/net-android/PublicAPI.Unshipped.txtsrc/Controls/src/Core/PublicAPI/net-ios/PublicAPI.Unshipped.txtsrc/Controls/src/Core/PublicAPI/net-maccatalyst/PublicAPI.Unshipped.txtsrc/Controls/src/Core/PublicAPI/net-tizen/PublicAPI.Unshipped.txtsrc/Controls/src/Core/PublicAPI/net-windows/PublicAPI.Unshipped.txtsrc/Controls/src/Core/PublicAPI/net/PublicAPI.Unshipped.txtsrc/Controls/src/Core/PublicAPI/netstandard/PublicAPI.Unshipped.txtsrc/Core/src/Handlers/Button/ButtonHandler.iOS.cssrc/Core/src/Platform/Android/ButtonExtensions.cssrc/Core/src/Platform/Android/ImageButtonExtensions.cssrc/Core/src/Platform/Android/MauiRippleDrawableExtensions.cssrc/Core/src/Platform/Android/RadioButtonExtensions.cssrc/Core/src/Platform/Android/StrokeExtensions.cssrc/Core/src/Platform/Android/ViewExtensions.cssrc/Core/src/Platform/Windows/ButtonExtensions.cssrc/Core/src/Platform/Windows/ContentPanel.cssrc/Core/src/Platform/Windows/DatePickerExtensions.cssrc/Core/src/Platform/Windows/PickerExtensions.cssrc/Core/src/Platform/Windows/RadioButtonExtensions.cssrc/Core/src/Platform/Windows/SearchBarExtensions.cssrc/Core/src/Platform/Windows/SliderExtensions.cssrc/Core/src/Platform/Windows/StepperExtensions.cssrc/Core/src/Platform/Windows/TextBoxExtensions.cssrc/Core/src/Platform/Windows/TimePickerExtensions.cssrc/Core/src/Platform/Windows/ViewExtensions.cssrc/Core/src/Platform/iOS/MauiCALayer.cssrc/Core/src/Platform/iOS/SearchBarExtensions.cssrc/Core/src/Platform/iOS/StrokeExtensions.cssrc/Core/src/Platform/iOS/ViewExtensions.cs
📋 Pre-Flight — Context & Validation
PR #36329 Pre-Flight
Context
- Title: Add support for background images with
ImageBrush - Issue: #12928, which requests a WPF-style
ImageBrushfor control and layout backgrounds. - Review branch:
pr-review-36329 - Base:
net11.0 - Merge base:
6801352a - Materialized PR commit:
68de6bf7a9 - Scope: 98 files, 1,305 insertions, 132 deletions, including implementation, public API baselines, UI-test coverage, and platform snapshots.
Existing PR Approach
The PR makes Microsoft.Maui.Controls.ImageBrush public and adds its API entries for every target. Platform background mappers then special-case ImageSourcePaint, asynchronously resolve its IImageSource, and assign a native image background:
- Android adds shared
Android.Views.Viewimage-background helpers and branches in button, image-button, radio-button, stroke, and general-view paths. - iOS/MacCatalyst adds
UIViewimage-background resolution,MauiCALayerimage storage, and branches in button, search-bar, stroke, and general-view paths. - Windows adds
FrameworkElementhelpers, updates image backgrounds across visual states, and branches in each affected control mapper. - The PR adds an
Issue12928host page, 13 screenshot UI tests, and snapshots for Android, iOS, MacCatalyst, and Windows.
Alternative candidates must use a different root-cause/design strategy rather than restating these per-control ImageSourcePaint branches.
Validation Boundary
- Primary test:
pwsh .github/scripts/BuildAndRunHostApp.ps1 -Platform ios -TestFilter "Issue12928" - Mandatory regression after the primary passes:
pwsh .github/scripts/BuildAndRunHostApp.ps1 -Platform ios -TestFilter "Issue34666" - Gate: Passed before STEP 5a.
Issue12928failed without the PR fix and all 13 tests passed with it. Do not rerun gate verification and do not modifygate/content.md. - Regression cross-reference:
src/Core/src/Platform/iOS/ViewExtensions.csoverlaps fix PR #36628 for #36501. The recorded PR implementation passedIssue34666; every alternative must independently pass it. - Platform: iOS only for this bounded phase. Do not run a full suite or tests beyond the two filters above.
Execution Constraints
Each candidate gets one implementation/test pass and no more than one focused correction/retest. It must perform the try-fix skill's inline expert self-review, capture its diff and complete test evidence, restore the baseline through EstablishBrokenBaseline.ps1 -Restore, and leave unrelated pre-existing tooling changes untouched.
🔬 Code Review — Deep Analysis
Expert PR Evaluation — PR #36329
Verdict: NEEDS_CHANGES
Confidence: medium
The submitted fix exposes ImageBrush publicly and adds native image-background handling across Android, iOS/MacCatalyst, and Windows. The broad wiring and screenshot coverage establish the intended rendering path, and the trusted Gate passed (Issue12928 fails without the fix and passes with it), but the implementation is not safe to merge as submitted.
The expert review produced 14 actionable inline findings in inline-findings.json. The blocking themes are:
- Shape clipping is incorrect: iOS
MauiCALayerand Android ripple/border paths draw image backgrounds outside rounded shapes. - Async image loads can overwrite newer state: uncancelled
FireAndForgetcontinuations on Android, iOS, and Windows do not verify that the requestedImageSourcePaintis still current. A slow image can replace a later solid brush or newer image. - Android text-input behavior regresses: the image path bypasses padding preservation and the standard
EditTextunderline restoration. - Transition and failure cleanup is incomplete: MacCatalyst buttons can retain an image layer after switching to a solid brush; null/failed sources can leave transparent or stale backgrounds;
MauiCALayercan retain its image. - Coverage omits the riskiest state transitions: the tests apply image brushes but do not exercise image-to-solid, image-to-image, or failed-source behavior.
The public API shape also warrants deliberate confirmation: ImageBrush becomes an unsealed public type with virtual state and value equality, creating a permanent subclassing/equality contract.
Required-check status could not be queried because the local GitHub CLI is unauthenticated. This does not change the verdict because the code review found concrete correctness defects. The trusted Gate result is recorded as passed, and no Gate verification was rerun.
🛠️ Try-Fix — Analysis & Comparison
Try-Fix Aggregate
Candidate 1 — Single iOS Paint-Pipeline Sink
Model: claude-opus-5
Result: Pass
Approach
Treat ImageSourcePaint as a missing arm in the existing iOS paint-to-platform sinks rather than teaching every control mapper about image backgrounds. The candidate added image handling to ViewExtensions.UpdateBackground(UIView, Paint?, IButtonStroke?) and MauiCALayer.SetBackground(Paint?), retained only the exceptional SearchBar and MacCatalyst button paths, and made MauiCALayer own version-guarded asynchronous image state. The public ImageBrush surface and its seven PublicAPI baselines remain necessary.
This differs from the PR's per-control branches by centralizing rendering at the two shared paint sinks. It also guards against stale asynchronous image loads.
Candidate Diff Scope
src/Core/src/Platform/iOS/ViewExtensions.cs(+16/-0)src/Core/src/Platform/iOS/MauiCALayer.cs(+58/-2)src/Core/src/Platform/iOS/SearchBarExtensions.cs(+6/-0)src/Core/src/Handlers/Button/ButtonHandler.iOS.cs(+8/-0; MacCatalyst-only)src/Controls/src/Core/ImageBrush.cs- Seven
PublicAPI.Unshipped.txtfiles
Unlike the PR, the candidate did not change StrokeExtensions.cs or ViewExtensions.UpdateBackground(UIView, IView).
The exact patch is preserved in try-fix/attempt-1/fix.diff and embedded in try-fix-1/content.md.
Test Results
| Test | Result |
|---|---|
BuildAndRunHostApp.ps1 -Platform ios -TestFilter "Issue12928" |
Pass — 13/13 |
BuildAndRunHostApp.ps1 -Platform ios -TestFilter "Issue34666" |
Pass — 1/1 |
One implementation/test pass was used; no correction was needed.
Analysis
The candidate reused the existing iOS image-source loading and layer rendering behavior while moving responsibility into shared paint sinks. The mandatory regression remained intact because the new image arm is additive and preserves PR #36628's background-layer removal path.
Inline self-review recorded three non-blocking findings: zero critical, zero major, two moderate, and one minor. Full findings and analysis are in try-fix/attempt-1/reviewer-findings.json and try-fix/attempt-1/analysis.md.
Baseline restoration completed and the tracked candidate changes were removed.
Candidate 2 — Handler-Lifecycle Background Decoration
Model: gpt-5.6-sol
Result: Fail
Approach
Intercept image backgrounds after normal mapper execution in the generic iOS handler lifecycle, resolve the image asynchronously with handler-scoped cancellation/version state, and render it in a dedicated auto-sizing StaticCALayer. Cleanup runs when the background changes and when the handler disconnects.
This differs from the PR by avoiding per-control branches, and from candidate 1 by leaving both shared paint sinks and MauiCALayer resolution unchanged. The generic handler lifecycle owns loading and stale-result protection while a separate decoration layer coexists with shape and stroke layers.
Candidate Diff Scope
src/Controls/src/Core/ImageBrush.cs- Seven
PublicAPI.Unshipped.txtfiles src/Core/src/Handlers/Element/ElementHandler.cssrc/Core/src/Handlers/View/ViewHandler.iOS.cs
The exact patch is preserved in try-fix/attempt-2/fix.diff and embedded in try-fix-2/content.md.
Test Results
| Test | Result |
|---|---|
Initial BuildAndRunHostApp.ps1 -Platform ios -TestFilter "Issue12928" |
Fail — RS0016 for a missing PublicAPI entry |
Corrected BuildAndRunHostApp.ps1 -Platform ios -TestFilter "Issue12928" |
Fail — 2/13 passed; 11 screenshot mismatches (0.54%–1.41%) |
BuildAndRunHostApp.ps1 -Platform ios -TestFilter "Issue34666" |
Not run because the primary never passed |
The candidate used its single permitted focused correction to address the PublicAPI compilation failure. No further correction was attempted.
Failure Analysis
The lifecycle hook rendered simple backgrounds, but a generic negative-Z decoration layer did not preserve composition for complex UIKit controls, shaped borders, scroll/item controls, and specialized handlers. It could also coexist with existing image-aware mappers, causing duplicate source resolution and temporary duplicate layers. Correcting those failures would require a different design or per-control exceptions beyond the bounded attempt.
Inline self-review recorded one moderate performance finding for duplicate image resolution/layers. Full findings and analysis are in try-fix/attempt-2/reviewer-findings.json and try-fix/attempt-2/analysis.md.
Baseline restoration completed and the tracked candidate changes were removed.
Aggregate Outcome
Two candidates were attempted. Candidate 1 passed both required iOS filters; candidate 2 failed the primary after its one allowed correction and therefore did not run the gated regression filter.
📝 PR Finalize — Recommended Title & Description
Assessment: ✏️ Recommend updating — the current title lacks a platform/component prefix, and the description incorrectly implies Tizen rendering changes while omitting several submitted mapper and test changes.
Recommended title
[Android/iOS/Windows] ImageBrush: Support image backgrounds on controls
Recommended description
## Description
`ImageBrush` already existed in Controls but was internal, and the native background mapping paths did not consistently handle its `ImageSourcePaint` representation. As a result, applications could not publicly use `ImageBrush` for control backgrounds, and the affected platform mappers did not asynchronously resolve and apply its `IImageSource`.
This pull request makes `ImageBrush` public and adds image-background handling for controls on Android, iOS/MacCatalyst, and Windows. Tizen receives the shared public `ImageBrush` API baseline, but this change does not add a Tizen-specific rendering path.
## Changes
### Public `ImageBrush` API
- Made `ImageBrush` public in `ImageBrush.cs`, including its constructors, `ImageSource` bindable property, `IsEmpty`, `Equals`, and `GetHashCode`.
- Added `ImageBrush` entries to `PublicAPI.Unshipped.txt` for Android, iOS, MacCatalyst, Tizen, Windows, .NET, and netstandard.
### Android
- Updated button, image-button, radio-button, border/stroke, text-input, and general-view background paths to recognize `ImageSourcePaint` before applying their default paint logic.
- Added shared `Android.Views.View` helpers that resolve the `IImageSourceServiceProvider` and apply image backgrounds asynchronously.
- Added image-aware ripple and stroke-layer composition for button and border backgrounds.
### iOS and MacCatalyst
- Updated button background mapping, including the MacCatalyst-specific button path, to handle `ImageSourcePaint`.
- Updated `SearchBarExtensions` and general `UIView` background mapping for image backgrounds.
- Added shared `UIView` image-source helpers and `MauiCALayer` image-background support for shaped/bordered views.
### Windows
- Updated background mapping for Button, DatePicker, Picker, RadioButton, SearchBar, Slider, Stepper, TextBox, TimePicker, and general `FrameworkElement` paths.
- Added `UpdateBackgroundImageForAllStates` to set image backgrounds for Normal, PointerOver, Pressed, Disabled, and Focused visual states.
- Added shared `FrameworkElement` image-source helpers and border/content-panel handling.
- Added the dedicated `UpdateTimePickerBackgroundImageAsync` path, which avoids `RefreshThemeResources` overwriting the programmatic image background through style setters.
### Tests
- Added the `Issue12928` HostApp test page covering image backgrounds across controls and layouts.
- Added 13 screenshot UI tests and platform baselines for Android, iOS, MacCatalyst, and Windows.
## Issues Fixed
Fixes #12928
## Output
| iOS | Mac | Android | Windows |
|---|---|---|---|
| <img src="https://github.com/user-attachments/assets/cb56d391-bfde-4547-a900-927ef27e7f0a"> | <img src="https://github.com/user-attachments/assets/322ddc61-9c0f-42d6-a5de-0203a8436511"> | <img src="https://github.com/user-attachments/assets/9c14ad79-94e6-42ef-ab5d-643e25c34921"> | <img src="https://github.com/user-attachments/assets/54eb634f-8f23-48d3-97be-7a0b516ac237"> |
## Issues / Limitations
- BoxView and GraphicsView are not supported by the image-background paths added here.
- RefreshView works only on Windows because iOS, MacCatalyst, and Android do not render its `Background`.
- WebView works only on iOS and MacCatalyst because Android and Windows do not render its `Background`.
- Windows IndicatorView templates do not render the `Background` property visually.
🏁 Report — Final Recommendation
⚠️ Final Recommendation: REQUEST CHANGES
Winner: pr-plus-reviewer
pr-plus-reviewer is the strongest candidate because it preserves the submitted PR's complete platform scope, corrects verified iOS stale-load and cleanup defects, fixes the MacCatalyst background transition, and repairs the new public type's equality/hash contract. Its only permitted runs passed Issue12928 (13/13) and the mandatory Issue34666 regression (1/1).
It is not the submitted PR HEAD, so the recommendation must be REQUEST CHANGES. In addition, the bounded iOS refinement leaves expert-confirmed Android and Windows risks unresolved; these need platform-appropriate fixes and coverage before merge.
Comparative ranking
| Rank | Candidate | Primary | Regression | Assessment |
|---|---|---|---|---|
| 1 | pr-plus-reviewer |
Pass — 13/13 | Pass — 1/1 | Best balance of feature completeness and iOS correctness. It guards async results against changed/disconnected handlers, removes stale MacCatalyst layers, releases retained layer images, and fixes ImageBrush.GetHashCode. |
| 2 | try-fix-1 |
Pass — 13/13 | Pass — 1/1 | Clean iOS paint-sink design with versioned MauiCALayer loads, but the ordinary UIView sink still uses the unguarded async helper, resolves services globally rather than from the handler, retains an image in the layer, and does not implement the PR's Android/Windows scope. |
| 3 | pr |
Gate pass — 13/13 | Pass — 1/1 | Broad implementation and good apply-state snapshots, but concrete stale async writes, MacCatalyst cleanup, Android clipping/text-input regressions, Windows transition problems, and an inconsistent public equality/hash contract make the submitted fix unsafe as-is. |
| 4 | try-fix-2 |
Fail — 2/13 after correction | Not run | The generic negative-Z lifecycle decoration does not preserve UIKit composition for 11 scenarios. Per the execution rule, this failed candidate ranks below every candidate that passed the regression. |
Expert finding reconciliation
- The raw expert pass emitted 14 inline findings. Verified iOS findings informed the consolidated refinement.
- The reported iOS rounded-shape clipping defect does not reproduce in the code path:
MauiCALayer.DrawInContextaddsGetClipPath()and callsClip()before invokingDrawBackground, so image drawing is already clipped. No redundant clip was added. - The refinement prevents late iOS image results from replacing newer backgrounds by requiring the same handler platform view and the same current
ImageSourcePaint.ImageSourceafter the await. - MacCatalyst's optimized button path now removes its old image layer before applying a non-image configuration, and
MauiCALayerno longer retains image state after paint replacement/disposal. - Android rounded-image clipping, Android
EditTextunderline/padding preservation, Android/Windows stale-load handling, null-source fallbacks, and transition-focused tests remain unresolved.
Required next change
Apply pr-plus-reviewer/reviewer.patch to the PR, then address the remaining Android and Windows expert findings with targeted platform coverage. The existing apply-only snapshots are not sufficient for image-to-solid, image-to-image, failed-source, rounded-shape, and Android text-input transitions.
🔗 Regression Cross-Reference
🔍 Regression Cross-Reference
⚠ Overlaps with prior bug-fix PRs — same files modified, but no exact line revert detected.
| File | Fix PR | Fixed issue(s) |
|---|---|---|
src/Core/src/Platform/iOS/ViewExtensions.cs |
#36628 | #36501 |
🧪 Regression Tests to Verify
These tests were added by the overlapping fix PRs. Running them to verify no side-effect regressions:
| Fix PR | Type | Test | Filter |
|---|---|---|---|
| #36628 | UITest | Issue34666 | Issue34666 |
🧪 Regression Test Results
✅ PASSED — 1 passed, 0 failed, 0 skipped
| Fix PR | Test | Type | Result |
|---|---|---|---|
| #36628 | Issue34666 | UITest | ✅ PASSED |
📱 UI Tests — Brush,ViewBaseTests
Detected UI test categories: Brush,ViewBaseTests
✅ Deep UI tests — 161 passed, 0 failed across 2 categories on platform-pool agent (replaces in-process counts above).
🧪 UI Test Execution Results (deep, platform pool)
| Category | Tests | Snapshot diffs |
|---|---|---|
Brush |
49/49 ✓ | — |
ViewBaseTests |
112/112 ✓ | — |
📎 Download drop-deep-uitests artifact (TRX + snapshot diffs) |
🧭 Next Steps — reviewer patch required (pr-plus-reviewer)
The reviewer-enhanced candidate won, so the submitted PR still needs those changes.
Why: pr-plus-reviewer preserves the submitted cross-platform implementation while correcting verified iOS stale-load, cleanup, MacCatalyst transition, and ImageBrush hash-contract defects; both required iOS filters passed. Android and Windows expert findings remain, so the submitted PR still requires changes.
Apply PRAgent/pr-plus-reviewer/reviewer.patch from the CopilotLogs
artifact (or follow the report's Required submitted-PR change), push the update, and run
the review again.
This comment has been minimized.
This comment has been minimized.
|
|
kubaflo
left a comment
There was a problem hiding this comment.
Could you please resolve the merge conflicts?
|
We plan to include this in .NET 12, so I’m closing this PR for now. |
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!
Description
This pull request introduces support for using image backgrounds on controls by adding and exposing the
ImageBrushclass, and updates platform-specific background mapping logic to handle image backgrounds consistently across Android, iOS, Windows, MacCatalyst, and Tizen.The main changes include making
ImageBrushpublic, updating public API files for all target platforms, and modifying background mapping functions to check for and apply image backgrounds before falling back to default logic.Changes
Image background support and API changes
ImageBrushclass public inImageBrush.csand exposed its properties and methods in the public API files for all platforms, enabling developers to use image backgrounds in their controls.ImageBrush(constructors, property accessors, overrides) to thePublicAPI.Unshipped.txtfiles for Android, iOS, MacCatalyst, Tizen, Windows, .NET, and netstandard.Platform-specific background handling improvements
Android:
iOS/MacCatalyst:
Windows:
Shared helpers to reduce duplication
Issues Fixed
Fixes #12928
Output
Issues / Limitations