Hey Guys,
I’m trying to test Maui Graphics in a Windows UserControl that I put on a Windows Form. My App looks like:
The problem I’m having is that when I click on the “Draw Lines” button, nothing happens. In other words, “skglControl1.Invalidate();” does not cause “skglControl1_PaintSurface” to get an Invalidate event.
Why not?
I put all my reproducible code on GitHub at:
CBrauer/Maui-Graphics-in-a-WIndows-UserControl (github.com)
Here is the code for the UserControl:
using System.Diagnostics;
using Microsoft.Maui.Graphics;
using Microsoft.Maui.Graphics.Skia;
using SkiaSharp.Views.Desktop;
namespace Maui_graphics_in_a_Windows_User_Control_on_a_Windows_form;
public partial class MauiGraphicsUserControl:UserControl {
public static class Graphics {
public static void RandomLines(ICanvas canvas, Random rand, float width, float height, int lines = 100) {
canvas.FillColor = Colors.Navy;
canvas.FillRectangle(0, 0, width, height);
canvas.StrokeColor = Colors.White.WithAlpha(.1f);
canvas.StrokeSize = 2;
for (int i = 0; i < lines; i++) {
float x1 = (float) rand.NextDouble() * width;
float x2 = (float) rand.NextDouble() * width;
float y1 = (float) rand.NextDouble() * height;
float y2 = (float) rand.NextDouble() * height;
canvas.DrawLine(x1, y1, x2, y2);
}
}
}
readonly Random Rand = new();
readonly int LineCount = 1000;
private static int canvasWidth, canvasHeight;
private static ICanvas? canvas { get; set; }
private bool clearScreen { get; set; } = true;
public MauiGraphicsUserControl() {
InitializeComponent();
}
public void Clear() {
Debug.WriteLine("at Clear");
clearScreen = true;
skglControl1.Invalidate();
skglControl1.Update();
}
public void DrawLines() {
Debug.WriteLine("at DrawLines");
clearScreen = false;
skglControl1.Invalidate();
skglControl1.Update();
}
private void skglControl1_PaintSurface(object sender, SKPaintGLSurfaceEventArgs e) {
Debug.WriteLine("entered skglControl1_PaintSurface");
canvas = new SkiaCanvas() {
Canvas = e.Surface.Canvas
};
canvasWidth = skglControl1.Width;
canvasHeight = skglControl1.Height;
if (clearScreen) {
Debug.WriteLine("doing Clear");
Debug.Assert(canvas is not null, "Oh crap, canvas is null");
canvas.FillColor = Colors.White;
canvas.FillRectangle(0, 0, canvasWidth, canvasHeight);
clearScreen = false;
return;
}
Debug.WriteLine("doing DrawLines");
Debug.Assert(canvas is not null, "Oh crap, canvas is null");
Graphics.RandomLines(canvas, Rand, canvasWidth, canvasHeight, LineCount);
}
private void skglControl1_SizeChanged(object sender, EventArgs e) {
skglControl1.Invalidate();
}
}