Build with XuiView Markdown

Build an interactive drawing surface

Build a tiny diagram editor with one card. Drag the card to move it; drag the empty background to pan the camera. On a host that routes magnification, zoom around the gesture anchor.

The important design choice is to keep the card in world coordinates and the camera in view coordinates. Panning changes the camera, not every object in the document.

using Xui.Core.Abstract.Events;
using Xui.Core.Canvas;
using Xui.Core.Math2D;
using Xui.Core.UI;
using Xui.Core.UI.Input;
using NFloat = System.Runtime.InteropServices.NFloat;

public sealed class DrawingSurface : View
{
    private Rect card = new(70, 170, 170, 120);
    private Vector pan;
    private NFloat zoom = 1;
    private int? pointer;
    private Point previous;
    private bool movingCard;
    private Point ToWorld(Point point) => new((point.X - Frame.X - pan.X) / zoom, (point.Y - Frame.Y - pan.Y) / zoom);
    public override void OnPointerEvent(ref PointerEventRef e, EventPhase phase)
    {
        if (phase != EventPhase.Bubble)
            return;
        if (e.Type == PointerEventType.Down && pointer is null && e.State.Button == PointerButton.Left)
        {
            previous = e.State.Position;
            movingCard = card.Contains(ToWorld(previous));
            pointer = e.PointerId;
            CapturePointer(e.PointerId, PointerGestures.Drag);
            InvalidateRender();
        }
        else if (e.PointerId == pointer && e.Type == PointerEventType.Move)
        {
            var delta = e.State.Position - previous;
            previous = e.State.Position;
            if (movingCard)
                card = new Rect(card.X + delta.X / zoom, card.Y + delta.Y / zoom, card.Width, card.Height);
            else
                pan += delta;
            InvalidateRender();
        }
        else if (e.PointerId == pointer && e.Type is PointerEventType.Up or PointerEventType.Cancel or PointerEventType.LostCapture)
            StopDrag();
    }

    public override void OnZoom(ref ZoomEventRef e)
    {
        if (!e.HasPosition || !NFloat.IsFinite(e.ScaleFactor) || e.ScaleFactor <= 0)
            return;
        // ZoomEventRef.Position stays in window coordinates; pointer positions are routed.
        var anchor = GlobalToLocal(e.Position);
        var world = ToWorld(anchor);
        zoom = NFloat.Clamp(zoom * e.ScaleFactor, (NFloat)0.5, 3);
        pan = new Vector(anchor.X - Frame.X - world.X * zoom, anchor.Y - Frame.Y - world.Y * zoom);
        e.Handled = true;
        InvalidateRender();
    }

    private void StopDrag()
    {
        int? captured = pointer;
        pointer = null;
        if (captured is int id)
            ReleasePointer(id);
        InvalidateRender();
    }

    protected override void OnDeactivate() => StopDrag();
    protected override void RenderCore(IContext context)
    {
        context.SetFill(new Color(0xFAF7FFFF));
        context.FillRect(Frame);
        context.Save();
        try
        {
            context.BeginPath();
            context.Rect(Frame);
            context.Clip();
            context.Translate((Frame.X + pan.X, Frame.Y + pan.Y));
            context.Scale((zoom, zoom));
            context.SetFill(new Color(0xEADCF5FF));
            for (int x = 0; x <= 600; x += 40)
                for (int y = 0; y <= 800; y += 40)
                    context.FillRect(new Rect(x, y, 3, 3));
            context.SetFill(new Color(pointer is not null && movingCard ? 0xD957A8FFu : 0x8538CEFFu));
            context.BeginPath();
            context.RoundRect(card, 16);
            context.Fill();
            context.SetFill(Colors.White);
            context.SetFont(new Font(20, "Inter"));
            context.TextAlign = TextAlign.Center;
            context.TextBaseline = TextBaseline.Middle;
            context.FillText("Drag me", card.Center);
        }
        finally
        {
            context.Restore();
        }

        context.SetFill(new Color(0x492571FF));
        context.SetFont(new Font(16, "Inter"));
        context.TextAlign = TextAlign.Center;
        context.FillText("Drag the card or pan the background", (Frame.Center.X, Frame.Y + 40));
    }
}
Interactive drawing surface: initial rendered view
Interactive drawing surface · C# source · SVG · Open demo

Use the same camera in both directions

Drawing translates by the frame origin and pan offset, then scales by zoom. ToWorld reverses those steps: subtract the frame origin and pan, then divide by zoom.

Pointer events arrive with positions mapped through ancestor view transforms. The default view still uses its arranged frame coordinates, so this sample subtracts Frame.X and Frame.Y explicitly. Do not subtract them again if you change the view's coordinate mapping to make its origin local.

On press, convert the pointer to world coordinates and test the card rectangle there. Store whether the drag started on the card. The choice stays fixed for that gesture so a background pan does not suddenly become a card drag when the pointer crosses the card.

Preserve a drag outside the view

Capture the pointer with the Drag gesture marker and remember its ID. On movement, card coordinates change by delta / zoom; the camera changes by the unscaled view delta. That makes a ten-pixel hand movement look like ten pixels on screen at any zoom.

Release capture on up, cancellation, lost capture, or deactivation. Clear the stored ID before release to tolerate capture-change callbacks. Ignore other pointer IDs while one drag is active.

This surface deliberately claims a drag immediately. Inside a scrolling page, that means dragging it manipulates the drawing instead of scrolling the parent. For a mixed gesture design, add a threshold or explicit tool mode rather than accidentally making both handlers own the same movement.

Keep the zoom anchor stationary

ZoomEventRef.Position is a window-space anchor, so convert it with GlobalToLocal before using the camera math. First find the world point under the anchor, update the positive clamped zoom, then recompute pan so that world point still lands at the same screen location.

The handler accepts only finite positive scale factors and sets Handled after applying them. Magnification delivery depends on the host. This sample does not turn two arbitrary touch contacts into a pinch recognizer, and it does not reinterpret wheel scrolling as zoom. Dragging and panning remain available when magnification is absent.

Keep editing state separate from decoration

The dot grid is a small fixed world-space grid; it is not infinite. The instruction label is drawn after restoring the camera transform so it stays in place. The viewport clip prevents the card from painting into surrounding UI.

For multiple objects, hit-test from front to back and store a stable selected-object identity. Add undo at the document-operation level, such as a completed move, instead of recording every pointer sample as a separate user action.