Skip to content

[Windows] Fix Image AspectFit when the bitmap is already decoded - #39343

Merged
kubaflo merged 2 commits into
dotnet:inflight/currentfrom
Empiree:fix/windows-image-aspectfit-decoded
Oct 15, 2026
Merged

kubaflo merged 2 commits into
dotnet:inflight/currentfrom
Empiree:fix/windows-image-aspectfit-decoded

Conversation

@Empiree

@Empiree Empiree commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

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 of Change

On Windows, an AspectFit image gets MaxWidth/MaxHeight from its pixel size in UpdatePlatformMaxConstraints, but this is only called from ImageOpened. WinUI doesnt raise ImageOpened for a source that is already decoded. That's the case for a WriteableBitmap from a custom image source service, and also for file path, stream and URI sources, they load a BitmapImage with SetSourceAsync. Then the platform image is bigger than its frame and the picture is cut off.

Now SetImageSource calls UpdatePlatformMaxConstraints when the new bitmap already has its size. Images that WinUI decodes itself (ms-appx) still go through ImageOpened like before.

Added two Windows device tests, one with an image from a file path and one with a WriteableBitmap. They are in ImageHandlerTests and not in the generic class, because ImageButtonHandler doesnt cap the image size.

I could not run device tests locally. I checked the change in a small Windows app with copy of ImageHandler from main, with and without the fix (screenshot below, top row is main). File path, stream and WriteableBitmap images now look like the ms-appx one, big images and Fill alignment don't change.

image

Issues Fixed

Fixes #34968

@Empiree
Empiree temporarily deployed to copilot-pat-pool October 12, 2026 17:54 — with GitHub Actions Inactive
@github-actions

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 39343

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 39343"

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service dotnet-policy-service Bot added the community ✨ Community Contribution label Oct 12, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Hey there @@Empiree! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

@Empiree
Empiree temporarily deployed to copilot-pat-pool October 12, 2026 17:55 — with GitHub Actions Inactive
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Hey there @Empiree! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

github-actions[bot]

This comment was marked as outdated.

@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Oct 13, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Note

🔍 /review gate started

AzDO build 15668490 is running for android.

The s/agent-review-in-progress label stays on this PR while existing PR tests are verified. The final gate report contains test evidence only: no expert review, alternative fixes, or Deep UI sweep runs.

@MauiBot

This comment has been minimized.

@MauiBot MauiBot removed the s/agent-review-in-progress AI review is currently running for this PR label Oct 13, 2026
@kubaflo kubaflo assigned Copilot and unassigned Copilot Oct 13, 2026
github-actions[bot]

This comment was marked as outdated.

@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Oct 14, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Note

🔍 /review started

AzDO build 15682288 is running for windows.

The s/agent-review-in-progress label stays on this PR through the full pipeline. The final AI Summary and outcome labels are posted only after Gate, expert review, and Deep UI tests finish.

github-actions[bot]

This comment was marked as outdated.

@kubaflo

kubaflo commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).

@kubaflo

This comment has been minimized.

@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Oct 14, 2026
@kubaflo

kubaflo commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).

github-actions[bot]

This comment was marked as outdated.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Expert Review

@Empiree — new AI review results are available based on commit 17c7af3.

Scope: Full PR (all commits) Expert review: Complete

✅ Merge recommendation: YES. No actionable findings.

🔬 Review details

Coverage: 6/6 dimensions; finding validation complete.

Dimensions:

  • ✅ 3. Handler Mapper and Property Patterns
  • ✅ 4. Architectural Layer Placement
  • ✅ 5. Logic and Correctness Verification
  • ✅ 6. Regression Prevention and Test Coverage
  • ✅ 7. Public API Surface Design
  • ✅ 16. Complexity Reduction

Context limitations (not code findings):

  • Discussion changed during the review. This recommendation assesses the frozen code and discussion available at review start.

AI source/history review only; no builds or tests run. Required CI and human approval still apply.

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI Review Summary

@Empiree — new AI review results are available based on commit 17c7af3.

Gate Passed Confidence Medium Platform Windows


🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix

Gate Result: ✅ PASSED

Platform: WINDOWS · Base: main · Merge base: 5375f6f8

Test Without Fix (expect FAIL) With Fix (expect PASS)
📱 BaseImageSourceServiceTests Category=ImageSource ⚠️ ENV ERROR ⚠️ ENV ERROR
📱 ImageHandlerTests (AspectFit_ImageFromFilePath_PlatformMaxSizeIsConstrainedToPixelSize, AspectFit_WriteableBitmap_PlatformMaxSizeIsConstrainedToPixelSize) Category=Image ✅ FAIL — 303s ✅ PASS — 302s
🔴 Without fix — 📱 BaseImageSourceServiceTests: ⚠️ ENV ERROR · 405s

No log file found

🟢 With fix — 📱 BaseImageSourceServiceTests: ⚠️ ENV ERROR · 302s

No log file found

🔴 Without fix — 📱 ImageHandlerTests (AspectFit_ImageFromFilePath_PlatformMaxSizeIsConstrainedToPixelSize, AspectFit_WriteableBitmap_PlatformMaxSizeIsConstrainedToPixelSize): FAIL ✅ · 303s

(no coded error found; showing last 1200 chars)

ss the warning by specifying `x:SuppressXamlTrimWarnings=True` within the closest element. If not, the property path might be trimmed and will not be AOT compatible. [D:\a\1\s\src\Controls\src\Core\Controls.Core.csproj::TargetFramework=net10.0-windows10.0.19041.0]
Platform\Windows\TabbedPage\TabbedPageStyle.xaml(13,13): XamlCompiler warning WMC1510: Ensure the property path is trimming and AOT compatible by making use of 'Compiled Bindings (x:bind)' if possible or by specifying the 'x:DataType' directive with the respective binding data context and marking the type declaration with the 'WinRT.GeneratedBindableCustomProperty' attribute or the 'Microsoft.UI.Xaml.Data.Bindable' attribute. If you are unable to do either but can ensure the data type is attributed correctly, then you can also suppress the warning by specifying `x:SuppressXamlTrimWarnings=True` within the closest element. If not, the property path might be trimmed and will not be AOT compatible. [D:\a\1\s\src\Controls\src\Core\Controls.Core.csproj::TargetFramework=net10.0-windows10.0.19041.0]
    0 Error(s)
Time Elapsed 00:04:49.04
  Passed: 0
  Failed: 2
  Skipped: 0
  Total: 2
  Tests completed with exit code: 1
🟢 With fix — 📱 ImageHandlerTests (AspectFit_ImageFromFilePath_PlatformMaxSizeIsConstrainedToPixelSize, AspectFit_WriteableBitmap_PlatformMaxSizeIsConstrainedToPixelSize): PASS ✅ · 302s

(no coded error found; showing last 1200 chars)

uppress the warning by specifying `x:SuppressXamlTrimWarnings=True` within the closest element. If not, the property path might be trimmed and will not be AOT compatible. [D:\a\1\s\src\Controls\src\Core\Controls.Core.csproj::TargetFramework=net10.0-windows10.0.19041.0]
Platform\Windows\TabbedPage\TabbedPageStyle.xaml(13,13): XamlCompiler warning WMC1510: Ensure the property path is trimming and AOT compatible by making use of 'Compiled Bindings (x:bind)' if possible or by specifying the 'x:DataType' directive with the respective binding data context and marking the type declaration with the 'WinRT.GeneratedBindableCustomProperty' attribute or the 'Microsoft.UI.Xaml.Data.Bindable' attribute. If you are unable to do either but can ensure the data type is attributed correctly, then you can also suppress the warning by specifying `x:SuppressXamlTrimWarnings=True` within the closest element. If not, the property path might be trimmed and will not be AOT compatible. [D:\a\1\s\src\Controls\src\Core\Controls.Core.csproj::TargetFramework=net10.0-windows10.0.19041.0]
    0 Error(s)
Time Elapsed 00:04:48.97
  Passed: 2
  Failed: 0
  Skipped: 0
  Total: 2
  Tests completed successfully

⚠️ Failure Details

  • ⚠️ BaseImageSourceServiceTests without fix: Device test result file(s) contained no tests for class(es) 'Microsoft.Maui.DeviceTests.BaseImageSourceServiceTests' (the target tests did not run). Total tests found in result file(s): 0.
  • ⚠️ BaseImageSourceServiceTests with fix: Device test result file(s) contained no tests for class(es) 'Microsoft.Maui.DeviceTests.BaseImageSourceServiceTests' (the target tests did not run). Total tests found in result file(s): 0.
📁 Fix files reverted (1 files)
  • src/Core/src/Handlers/Image/ImageHandler.Windows.cs

📋 Pre-Flight — Context & Validation

Pre-Flight Context

Scope: Context only for #39343, based on the supplied immutable diff and submitted head 17c7af340a78ad6d1e38ea136b082d4850ddf449 against main at 55c13777e63b59463a5308e245455996b15b297f. No commands, tests, edits, alternatives, or review artifacts were produced. This is not an exhaustive code review.

Reported problem

  • #34968 reports that on Windows, Image with Aspect.AspectFit can render larger than its frame and become clipped when its image service returns an already-decoded WriteableBitmap.
  • The issue attributes this to WinUI not raising ImageOpened for that source. MAUI previously applied intrinsic-size MaxWidth/MaxHeight constraints from OnImageOpened, so that path was skipped.
  • Follow-up investigation reports the same behavior for rooted file paths, streams, and URI sources because their Windows services construct a BitmapImage and await SetSourceAsync before assigning it to the WinUI Image.
  • The issue is Windows-only, labeled as a regression beginning with .NET 10 RC2, and targeted to the .NET 10 SR12 milestone. Reported affected versions include 10.0.0-rc.2 through 10.0.51; the exact Windows OS-version range is unknown.

Existing mechanism and submitted change

The Windows handler currently:

  1. Subscribes to WinUI ImageOpened when connected.
  2. Clears _cachedImageSize and resets platform maximums to infinity before loading a new source.
  3. On ImageOpened, reads positive BitmapSource.PixelWidth/PixelHeight, caches them, updates animation state, and calls UpdatePlatformMaxConstraints().
  4. For AspectFit, caps each non-Fill alignment axis to the lesser of the intrinsic pixel dimension and the virtual view’s declared maximum. Other aspects use the declared maximums.
  5. In GetDesiredSize, prefers live bitmap dimensions and falls back to _cachedImageSize.

The submitted setter still assigns image.Source = platformImage, then additionally calls UpdatePlatformMaxConstraints() when:

  • The assigned source is a BitmapSource.
  • Both pixel dimensions are already positive.
  • The owning handler is specifically ImageHandler.

This reuses the live-size path in UpdatePlatformMaxConstraints; it does not populate _cachedImageSize. Sources whose dimensions are still zero continue to rely on the existing ImageOpened path. Packaged ms-appx images remain on that asynchronous WinUI decode path.

The Windows source path supports the stated mechanism:

  • Rooted file sources await BitmapImage.SetSourceAsync.
  • Stream and URI services likewise await SetSourceAsync.
  • A custom service can return an already-sized WriteableBitmap.
  • The source loader checks cancellation/source identity before invoking the setter.
  • ImageButtonHandler is intentionally excluded because it does not apply these image-size caps.

Changed files

File Change
src/Core/src/Handlers/Image/ImageHandler.Windows.cs After source assignment, detects an already-sized BitmapSource and immediately reapplies AspectFit platform maximum constraints.
src/Core/tests/DeviceTests/Handlers/Image/ImageHandlerTests.Windows.cs Adds Windows device tests for a rooted file-path source and a directly assigned WriteableBitmap, scoped to ImageHandler rather than the generic ImageButtonHandler test surface.
src/Core/tests/DeviceTests/Services/ImageSource/BaseImageSourceServiceTests.Windows.cs Flushes the PNG encoder before rewinding the generated stream, preventing the file helper from producing an empty image.

The file-path test creates a 60x30 PNG on the UI thread, loads it through FileImageSourceStub, verifies decoded dimensions, and checks both maximum dimensions against the bitmap dimensions. The WriteableBitmap test invokes the source-loader setter directly and checks the same constraints. Both use centered horizontal and vertical alignment with AspectFit.

An existing Windows test already covers the later-decoding ImageOpened path using packaged red.png, including GetDesiredSize constraints and source-transition cache behavior.

Platform-sensitive paths

  • Windows/WinUI only: behavior depends on Microsoft.UI.Xaml.Controls.Image, BitmapSource.PixelWidth/PixelHeight, WriteableBitmap, and WinUI ImageOpened semantics.
  • UI-thread sensitivity: creating the test WriteableBitmap requires the Windows UI thread; the file helper invocation was moved inside InvokeOnMainThreadAsync.
  • Decode timing: packaged resources are decoded after assignment, while rooted files, streams, URIs, and prebuilt writable bitmaps can have dimensions before assignment.
  • Layout behavior: only AspectFit and non-Fill alignment axes receive intrinsic-size caps. Fill axes and non-AspectFit modes retain declared maximum constraints.
  • No public API change: all production changes are private Windows handler behavior.

Validation context and requirements

  • Required platform: Windows.
  • Supplied Gate result: ✅ PASSED — the relevant tests fail without the fix and pass with the fix. This result was not re-run.
  • The PR author reports manual comparison in a Windows app for file, stream, WriteableBitmap, and packaged-resource paths, including large images and Fill alignment. Those manual observations were not independently verified here.
  • Later validation should preserve both source-loading modes: already-decoded assignment and deferred WinUI decoding. It should also account for source transitions, declared maximum dimensions, independent horizontal/vertical Fill alignment, and non-AspectFit behavior.

Remaining uncertainties

  • The new automated coverage directly exercises a rooted file and the setter with a WriteableBitmap; it does not exercise a complete custom image-source-service registration, stream source, or URI source.
  • The direct WriteableBitmap test verifies the setter mechanism rather than the full asynchronous source-service lifecycle.
  • The tests assert platform MaxWidth/MaxHeight, not final visual clipping, rendered aspect ratio, or measured bounds in a complete application layout.
  • Both new tests use centered alignment and one 60x30 bitmap; other alignment combinations, declared maximums, display densities, animated images, and repeated source replacement are not directly covered by them.
  • A resolved review thread noted that the zero-dimension guard lacks a dedicated negative-path test. The author’s response points to source-cache clearing and the existing deferred-decode test, but the guard itself remains indirectly covered.
  • Exact Windows runtime versions and the detailed test-run/build identifiers behind the supplied passing Gate are unavailable here and therefore unknown.

🔬 Code Review — Deep Analysis

Expert Review — PR #39343

Independent Assessment

The submitted Windows fix updates ImageImageSourcePartSetter.SetImageSource to reapply the existing platform maximum-constraint calculation immediately when an assigned BitmapSource already exposes positive pixel dimensions. Deferred-decode sources continue through the existing ImageOpened path. The accompanying device tests cover rooted file-path and WriteableBitmap sources, while the image-source test helper now flushes its PNG encoder before rewinding the stream.

Findings

No actionable defects were found on submitted changed lines. The required inline findings artifact contains an empty JSON array.

Blast Radius and Failure-Mode Probes

  • The production change is limited to Windows ImageHandler; ImageButtonHandler, non-BitmapSource values, and zero-dimension/deferred-decode sources retain their existing paths.
  • No startup behavior, static/shared state, subscriptions, or lifecycle latches are introduced.
  • Already-decoded file, stream, URI, and writable-bitmap sources can receive constraints at assignment time; packaged/deferred sources remain handled by ImageOpened.
  • Existing UpdatePlatformMaxConstraints logic preserves non-AspectFit and Fill-axis behavior.

Validation Evidence

  • Trusted Gate: ✅ PASSED — the relevant tests fail without the submitted fix and pass with it.
  • The expert task could not independently classify live required-check state, but that does not replace or invalidate the caller-supplied Gate result.
  • Platform-handler scope caps confidence at medium.

Verdict: LGTM

Confidence: medium

The submitted change matches the Windows decode-timing failure mechanism, is narrowly scoped, and has regression evidence from the trusted Gate. No blocking expert findings or discussion items remain.

Refinement Threshold

Not met. The expert review identified neither a concrete actionable defect nor an unresolved behavioral mechanism backed by source or test evidence, so no pr-plus-reviewer candidate is generated.


🛠️ Try-Fix — Analysis & Comparison

Alternative generation: not requested

Evidence-first mode intentionally omits routine Try-Fix attempts. This is not a failed
attempt, a completed alternative search, or evidence that alternatives have no value.
The expert review may still produce one evidence-backed PR refinement.


🏁 Report — Final Recommendation

✅ Final Recommendation: APPROVE

Phase Status

Phase Status Notes
Pre-Flight ✅ COMPLETE Trusted evidence-first context consumed
Expert Review LGTM (medium) 0 errors, 0 warnings, no inline findings
Gate ✅ PASSED Windows tests fail without the fix and pass with it
Try-Fix Not requested Evidence-first mode intentionally omitted routine alternatives
Refinement Not generated Expert evidence did not meet the refinement threshold
Report ✅ COMPLETE Sole real candidate compared

Code Review and Candidate Comparison

Candidate Validation Expert findings addressed Result
pr ✅ Trusted Gate passed No blocking findings identified Winner

No pr-plus-reviewer candidate was implemented because the expert review found no concrete actionable defect or unresolved behavioral mechanism. No try-fix-* candidates exist; alternative generation was intentionally not requested.

Summary

The raw submitted PR is the only real candidate and wins. It narrowly fixes the Windows already-decoded image path, preserves deferred decoding through ImageOpened, and has regression evidence from the trusted Gate. The expert review found no blocking errors or discussion items.

Root Cause

Windows can assign a BitmapSource whose dimensions are already available without raising ImageOpened. Because AspectFit maximum constraints were previously updated only from that event, the platform image could remain larger than its frame and be clipped.

Fix Quality

The setter reuses the existing UpdatePlatformMaxConstraints behavior only for positive-dimension BitmapSource values owned by ImageHandler. The change introduces no public API, shared state, lifecycle subscription, or alternate constraint algorithm. Added Windows device coverage exercises rooted file-path and WriteableBitmap sources, and the PNG test helper now flushes encoded data before rewind.

Evidence Gaps

The new tests assert platform maximum constraints rather than final rendered bounds, and stream/URI services are supported by the same mechanism but are not directly covered by the added tests. Live required-check state was not independently classified by the expert task; the recommendation relies on the trusted caller's passing Gate and does not claim evidence beyond that validation.


📱 UI Tests — ViewBaseTests

Detected UI test categories: ViewBaseTests

⚠️ Deep UI tests — 94 passed; 1 category (21 tests) could not run: OneTimeSetUp/fixture setup failure on the platform-pool agent — infrastructure, not a PR test failure (replaces in-process counts above).

🧪 UI Test Execution Results (deep, platform pool)

Category Tests Snapshot diffs
ViewBaseTests 94/115 (setup failed; 21 marked failed) —
⚠️ ViewBaseTests — fixture setup failed for 21 tests

NUnit reported a OneTimeSetUp/fixture setup failure before test bodies ran; the TRX marked each affected test failed.

OneTimeSetUp: System.TimeoutException : Timed out waiting for Go To Test button to disappear
at UITest.Appium.HelperExtensions.Wait(Func`1 query, Func`2 satisfactory, String timeoutMessage, Nullable`1 timeout, Nullable`1 retryFrequency) in /_/src/TestUtils/src/UITest.Appium/HelperExtensions.cs:line 2790
   at UITest.Appium.HelperExtensions.WaitForNone(Func`1 query, String timeoutMessage, Nullable`1 timeout, Nullable`1 retryFrequency) in /_/src/TestUtils/src/UITest.Appium/HelperExtensions.cs:line 2826
   at UITest.Appium.HelperExtensions.WaitForNoElement(IApp app, String marked, String timeoutMessage, Nullable`1 timeout, Nullable`1 retryFrequency, Nullable`1 postTimeout) in /_/src/TestUtils/src/UITest.Appium/HelperExtensions.cs:line 1031
   at Microsoft.Maui.TestCases.Tests.UtilExtensions.NavigateTo(IApp app, String text) in /_/src/Controls/tests/TestCases.Shared.Tests/UtilExtensions.cs:line 104
   at Microsoft.Maui.TestCases.Tests.UtilExtensions.NavigateToGallery(IApp app, String page) in /_/src/Controls/tests/TestCases.Shared.Tests/UtilExtensions.cs:line 38
   at Microsoft.Maui.TestCases.Tests._GalleryUITest.FixtureSetup() in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/_GalleryUITest.cs:line 57
   at UITest.Appium.NUnit.UITestBase.OneTimeSetup() in /_/src/TestUtils/src/UITest.NUnit/UITestBase.cs:line 221
   at System.RuntimeMethodHandle.InvokeMethod(ObjectHandleOnStack target, Void** arguments, ObjectHandleOnStack sig, BOOL isConstructor, ObjectHandleOnS
...

📎 Download drop-deep-uitests artifact (TRX + snapshot diffs)


🧭 Next Steps — review latest findings

No alternative fix was selected for this run. Review the session findings and CI results before merging.

@MauiBot MauiBot added s/agent-approved AI agent recommends approval - PR fix is correct and optimal s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) and removed s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-gate-failed AI could not verify tests catch the bug s/agent-review-in-progress AI review is currently running for this PR labels Oct 14, 2026
@kubaflo
kubaflo changed the base branch from main to inflight/current October 15, 2026 12:21
@kubaflo
kubaflo merged commit e9e230d into dotnet:inflight/current Oct 15, 2026
190 of 200 checks passed
@github-actions github-actions Bot added this to the .NET 10 SR12 milestone Oct 15, 2026
kubaflo pushed a commit that referenced this pull request Oct 18, 2026
)

<!-- 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!

### Description of Change

On Windows, an AspectFit image gets MaxWidth/MaxHeight from its pixel
size in `UpdatePlatformMaxConstraints`, but this is only called from
`ImageOpened`. WinUI doesnt raise `ImageOpened` for a source that is
already decoded. That's the case for a `WriteableBitmap` from a custom
image source service, and also for file path, stream and URI sources,
they load a `BitmapImage` with `SetSourceAsync`. Then the platform image
is bigger than its frame and the picture is cut off.

Now `SetImageSource` calls `UpdatePlatformMaxConstraints` when the new
bitmap already has its size. Images that WinUI decodes itself (ms-appx)
still go through `ImageOpened` like before.

Added two Windows device tests, one with an image from a file path and
one with a `WriteableBitmap`. They are in `ImageHandlerTests` and not in
the generic class, because `ImageButtonHandler` doesnt cap the image
size.

I could not run device tests locally. I checked the change in a small
Windows app with copy of `ImageHandler` from main, with and without the
fix (screenshot below, top row is main). File path, stream and
WriteableBitmap images now look like the ms-appx one, big images and
Fill alignment don't change.

<img width="1703" height="619" alt="image"
src="https://github.com/user-attachments/assets/e10f3025-6acf-4d3e-bfb9-149e31c12a2f"
/>

### Issues Fixed

Fixes #34968

---------

Co-authored-by: Empiree <Empiree@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Oct 21, 2026
)

<!-- 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!

### Description of Change

On Windows, an AspectFit image gets MaxWidth/MaxHeight from its pixel
size in `UpdatePlatformMaxConstraints`, but this is only called from
`ImageOpened`. WinUI doesnt raise `ImageOpened` for a source that is
already decoded. That's the case for a `WriteableBitmap` from a custom
image source service, and also for file path, stream and URI sources,
they load a `BitmapImage` with `SetSourceAsync`. Then the platform image
is bigger than its frame and the picture is cut off.

Now `SetImageSource` calls `UpdatePlatformMaxConstraints` when the new
bitmap already has its size. Images that WinUI decodes itself (ms-appx)
still go through `ImageOpened` like before.

Added two Windows device tests, one with an image from a file path and
one with a `WriteableBitmap`. They are in `ImageHandlerTests` and not in
the generic class, because `ImageButtonHandler` doesnt cap the image
size.

I could not run device tests locally. I checked the change in a small
Windows app with copy of `ImageHandler` from main, with and without the
fix (screenshot below, top row is main). File path, stream and
WriteableBitmap images now look like the ms-appx one, big images and
Fill alignment don't change.

<img width="1703" height="619" alt="image"
src="https://github.com/user-attachments/assets/e10f3025-6acf-4d3e-bfb9-149e31c12a2f"
/>

### Issues Fixed

Fixes #34968

---------

Co-authored-by: Empiree <Empiree@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Oct 25, 2026
)

<!-- 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!

### Description of Change

On Windows, an AspectFit image gets MaxWidth/MaxHeight from its pixel
size in `UpdatePlatformMaxConstraints`, but this is only called from
`ImageOpened`. WinUI doesnt raise `ImageOpened` for a source that is
already decoded. That's the case for a `WriteableBitmap` from a custom
image source service, and also for file path, stream and URI sources,
they load a `BitmapImage` with `SetSourceAsync`. Then the platform image
is bigger than its frame and the picture is cut off.

Now `SetImageSource` calls `UpdatePlatformMaxConstraints` when the new
bitmap already has its size. Images that WinUI decodes itself (ms-appx)
still go through `ImageOpened` like before.

Added two Windows device tests, one with an image from a file path and
one with a `WriteableBitmap`. They are in `ImageHandlerTests` and not in
the generic class, because `ImageButtonHandler` doesnt cap the image
size.

I could not run device tests locally. I checked the change in a small
Windows app with copy of `ImageHandler` from main, with and without the
fix (screenshot below, top row is main). File path, stream and
WriteableBitmap images now look like the ms-appx one, big images and
Fill alignment don't change.

<img width="1703" height="619" alt="image"
src="https://github.com/user-attachments/assets/e10f3025-6acf-4d3e-bfb9-149e31c12a2f"
/>

### Issues Fixed

Fixes #34968

---------

Co-authored-by: Empiree <Empiree@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Oct 26, 2026
)

<!-- 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!

### Description of Change

On Windows, an AspectFit image gets MaxWidth/MaxHeight from its pixel
size in `UpdatePlatformMaxConstraints`, but this is only called from
`ImageOpened`. WinUI doesnt raise `ImageOpened` for a source that is
already decoded. That's the case for a `WriteableBitmap` from a custom
image source service, and also for file path, stream and URI sources,
they load a `BitmapImage` with `SetSourceAsync`. Then the platform image
is bigger than its frame and the picture is cut off.

Now `SetImageSource` calls `UpdatePlatformMaxConstraints` when the new
bitmap already has its size. Images that WinUI decodes itself (ms-appx)
still go through `ImageOpened` like before.

Added two Windows device tests, one with an image from a file path and
one with a `WriteableBitmap`. They are in `ImageHandlerTests` and not in
the generic class, because `ImageButtonHandler` doesnt cap the image
size.

I could not run device tests locally. I checked the change in a small
Windows app with copy of `ImageHandler` from main, with and without the
fix (screenshot below, top row is main). File path, stream and
WriteableBitmap images now look like the ms-appx one, big images and
Fill alignment don't change.

<img width="1703" height="619" alt="image"
src="https://github.com/user-attachments/assets/e10f3025-6acf-4d3e-bfb9-149e31c12a2f"
/>

### Issues Fixed

Fixes #34968

---------

Co-authored-by: Empiree <Empiree@users.noreply.github.com>
github-actions Bot pushed a commit that referenced this pull request Oct 28, 2026
)

<!-- 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!

### Description of Change

On Windows, an AspectFit image gets MaxWidth/MaxHeight from its pixel
size in `UpdatePlatformMaxConstraints`, but this is only called from
`ImageOpened`. WinUI doesnt raise `ImageOpened` for a source that is
already decoded. That's the case for a `WriteableBitmap` from a custom
image source service, and also for file path, stream and URI sources,
they load a `BitmapImage` with `SetSourceAsync`. Then the platform image
is bigger than its frame and the picture is cut off.

Now `SetImageSource` calls `UpdatePlatformMaxConstraints` when the new
bitmap already has its size. Images that WinUI decodes itself (ms-appx)
still go through `ImageOpened` like before.

Added two Windows device tests, one with an image from a file path and
one with a `WriteableBitmap`. They are in `ImageHandlerTests` and not in
the generic class, because `ImageButtonHandler` doesnt cap the image
size.

I could not run device tests locally. I checked the change in a small
Windows app with copy of `ImageHandler` from main, with and without the
fix (screenshot below, top row is main). File path, stream and
WriteableBitmap images now look like the ms-appx one, big images and
Fill alignment don't change.

<img width="1703" height="619" alt="image"
src="https://github.com/user-attachments/assets/e10f3025-6acf-4d3e-bfb9-149e31c12a2f"
/>

### Issues Fixed

Fixes #34968

---------

Co-authored-by: Empiree <Empiree@users.noreply.github.com>
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 15, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

community ✨ Community Contribution s/agent-approved AI agent recommends approval - PR fix is correct and optimal s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Image.Aspect = Aspect.AspectFit breaks on Windows when using a WriteableBitmap as the ImageServiceResult for an ImageSource

4 participants