Color legend plain property dependency property method event
Every element here has all the properties, events and methods of BaseElement, which the
tables below don’t repeat. Names are colored by what they are: a plain property, a method, an event or a dependency property: Foo is backed by
FooDP, which a style, a binding or an animation can set (see styles, bindings and animation).
Screenshots use the theme from styles.
Image Style
Draws a texture, stretched over the image, centered at its own size or repeated as tiles.
Stretch, Center and Tile.var mark = LoadTexture("CheckBox/Checked.png"); // 64 x 64
Image Framed(Texture2D texture, ImageFill fill, int left) => new()
{
Source = texture,
Fill = fill,
DesiredWidth = 140,
DesiredHeight = 120,
BackgroundColor = new Color(40, 31, 23),
Margin = (left, 16)
};
// the whole texture over the image
ui.AddElementToRoot(Framed(mark, ImageFill.Stretch, 16));
// its own size, in the middle
ui.AddElementToRoot(Framed(mark, ImageFill.Center, 186));
// repeated, cut at the edges
ui.AddElementToRoot(Framed(mark, ImageFill.Tile, 356));
Source takes a Texture2D or a content path: both convert to a SourceData by themselves. A path is
loaded through the ContentManager you gave BorrowedTorchUI, so it names a compiled .xnb asset, without the
extension. A PNG file that is not a compiled asset can’t be read that way: load it with Texture2D.FromStream and give
the image the texture.
// a PNG file next to the executable
var path = Path.Combine(AppContext.BaseDirectory, "Content", "Pattern.png");
using var stream = File.OpenRead(path);
var pattern = Texture2D.FromStream(GraphicsDevice, stream);
var background = new Image("background") { Source = pattern, Fill = ImageFill.Tile };
// Badge.xnb, through the ContentManager
var badge = new Image("badge") { Source = "UITextures/Badge" };
The image never disposes its source. A texture you loaded yourself is yours to dispose when the game unloads; one
loaded from a path belongs to the ContentManager.
The source is drawn straight to the screen every frame, not kept in a texture of the image’s size. An image costs no texture memory of its own and can be larger than the GPU’s texture size limit, for example a tiled background of a long scrolled page. With the tile modes only the tiles in view are drawn. A parent that crops the image (a scrollable container) cuts it with a scissor rectangle.
An image without a size of its own that fits its content takes the size of its source, in units, and setting a new
source lays it out again. With the default Stretch alignment it fills its parent instead. The texture is tinted by
ForegroundColor, which is white by default (no change), and follows Transparency and the disabled shading like any
element.
ImageFill
| Value | Meaning |
|---|---|
Stretch |
The whole texture is stretched over the image. The default. |
Center |
The texture at its own size in the middle of the image. A texture larger than the image is cut at its edges. |
Tile |
The texture is repeated from the top left corner in both directions. The last tiles are cut at the right and bottom edges, not squeezed. |
TileX |
Repeated along the width, stretched over the height. |
TileY |
Repeated along the height, stretched over the width. |
Image properties
| Property | Type | Description |
|---|---|---|
Source |
SourceData |
The texture drawn. Assign a Texture2D or a content path. A new source lays the image out again. |
Fill |
ImageFill |
How the texture covers the image. Defaults to Stretch. |
Image methods
| Method | Description |
|---|---|
Image(string name = null) |
Creates an image. The name is used by GetElementByName. |
SourceData
The value of Image.Source: a wrapper around a texture that you rarely write yourself, since a Texture2D or a
content path converts to it. It doesn’t own the texture. Two SourceData are equal when they wrap the same texture
instance.
| Property | Type | Description |
|---|---|---|
Width |
int |
Read-only. The texture’s width in pixels, 0 without a texture. |
Height |
int |
Read-only. The texture’s height in pixels, 0 without a texture. |
IsEmpty |
bool |
Read-only. Whether there is nothing to draw: no texture, or a width or height of 0. |
| Method | Description |
|---|---|
SourceData(Texture2D texture) |
Wraps the texture. |
implicit operator SourceData(Texture2D texture) |
Lets you assign a texture where a SourceData is expected. |
implicit operator SourceData(string path) |
Loads the content path as a Texture2D through the UI’s ContentManager and wraps it. |
implicit operator Texture2D(SourceData data) |
Gives back the wrapped texture (null when it wraps none). |
operator == / operator != |
Compare a SourceData with another SourceData, a Texture2D or a content path, in either order, by texture instance. Comparing with a path loads that path through the ContentManager. |
Equals(object obj) |
Whether obj is a SourceData wrapping the same texture instance. |
GetHashCode() |
The hash code of the wrapped texture, 0 without one. |
Style class: ImageStyle (Source and Fill; it sets ForegroundColor to white, see styles).
Stencil Style
Shows a picture through a mask texture: where the mask has the key color, the picture shows, and the rest of the mask stays. A portrait in a frame is the usual case.
var portrait = new Stencil("portrait")
{
SourceTexture = LoadTexture("Stencil/Source.png"), // the picture
// the frame: half transparent black where the picture shows
StencilTexture = LoadTexture("Stencil/Stencil.png"),
KeyColor = new Color(0, 0, 0, 128), // the alpha is compared too
Tolerance = 0.2f,
DesiredWidth = 152,
DesiredHeight = 144,
Margin = (16, 16)
};
ui.AddElementToRoot(portrait);
Both textures are scaled to the stencil’s size, one pixel for every device pixel it covers, and then combined pixel by
pixel. A stencil pixel is replaced by the source pixel at the same place when its red, green and blue are within
Tolerance of KeyColor (the distance between the two colors, with each channel from 0 to 1) and its alpha is within
Tolerance of the key’s alpha as well. Every other stencil pixel stays as it is.
The alpha counts: the hole of this stencil is half transparent black, so the key is new Color(0, 0, 0, 128). The
opaque Color.Black with a small tolerance would not key it, and the hole would stay dark.
The result is computed on the CPU and kept in a texture, so a stencil costs texture memory (the two scaled textures and
the result, each of its device size). It is computed again only when a texture, the size, KeyColor or Tolerance
changes, not every frame. The result is shown by an inner Image stretched over the stencil.
The two textures are scaled on the GPU, each drawn into a render target of its own. The stencil then sets back the render targets that were set before, so it also works in a UI drawn into a render target of yours (see drawing into a render target).
A stencil without a size of its own that fits its content takes the size of StencilTexture. It takes no items: it is
made of its own parts only. The stencil doesn’t dispose the textures you give it.
Stencil properties
| Property | Type | Description |
|---|---|---|
SourceTexture |
Texture2D |
The picture that shows where the stencil has the key color. Not part of StencilStyle. |
StencilTexture |
Texture2D |
The mask drawn over the picture. A stencil that fits its content takes its size. Not part of StencilStyle. |
KeyColor |
Color |
The stencil color, alpha included, where the source shows through. Defaults to transparent black (0, 0, 0, 0). |
Tolerance |
float |
How far a stencil pixel may be from KeyColor and still be keyed, on a 0 to 1 scale per channel. Defaults to 0 (an exact match). |
Stencil methods
| Method | Description |
|---|---|
Stencil(string name = null) |
Creates a stencil. The name is used by GetElementByName. |
Style class: StencilStyle (KeyColor and Tolerance, see styles).
ViewPort Style
Reserves a rectangle in the layout and runs your own drawing code inside it, for a 3D scene, a minimap or any other render embedded in the UI.
var logo = LoadTexture("Logo/Kindling.png");
var batch = new SpriteBatch(GraphicsDevice);
var angle = 0.5f;
var scene = new ViewPort("scene")
{
DesiredWidth = 280,
DesiredHeight = 168,
BackgroundColor = new Color(8, 6, 4),
Margin = 16
};
// runs inside the view port, drawing from its top left corner; DeviceBounds is its
// rectangle in device pixels (GraphicsDevice.Viewport is set to it meanwhile)
scene.DrawInstructions = () =>
{
var bounds = scene.DeviceBounds;
var size = Math.Min(bounds.Width, bounds.Height) * 0.7f;
batch.Begin();
batch.Draw(logo,
new Vector2(bounds.Width / 2f, bounds.Height / 2f),
null,
Color.White,
angle,
new Vector2(logo.Width / 2f, logo.Height / 2f),
size / logo.Width,
SpriteEffects.None,
0f);
batch.End();
};
ui.AddElementToRoot(scene);
DrawInstructions runs while the UI draws, after the view port’s background and before its children, so
elements added to the view port with AddItem (a caption, buttons over a 3D scene) lie on top of your drawing.
Before it runs, the UI ends its sprite batch and sets three device states:
GraphicsDevice.Viewportis the view port’s whole rectangle in device pixels (DeviceBounds), withMinDepthandMaxDepthas its depth range. Draw relative to it:(0, 0)is the view port’s top left corner, and its size isDeviceBounds.WidthandHeight, the same asGraphicsDevice.Viewport.WidthandHeight(which drawing code written for the whole screen already reads). The drawing is not scaled by the UI’s display scale, so size it by these device pixels.GraphicsDevice.ScissorRectangleis the part of the view port that is on screen (itsHitRectangle, in device pixels). The viewport keeps its full size when a parent crops the view port, so the projection of your drawing does not change while it scrolls.GraphicsDevice.RasterizerStateis a state withScissorTestEnableset, so draws that keep it are cut to the visible part.
Afterwards the viewport, the scissor rectangle and the rasterizer state are restored and the UI’s sprite batch starts
again. The instructions are skipped while DrawInstructions is null, while the view port is hidden, has no size, or is
cropped away entirely.
SpriteBatch.Begin() sets its own rasterizer state, and without one it uses RasterizerState.CullCounterClockwise,
which has no scissor test. Your drawing then spills over the edges of a view port that a parent crops (a scrollable
container). Give your own batches a rasterizer state with the scissor test on; create it once, not every frame:
var clipped = new RasterizerState { ScissorTestEnable = true };
batch.Begin(rasterizerState: clipped); // cut to scene.HitRectangle
A view port doesn’t take the mouse by default (its style sets HitTest to false).
ViewPort properties
| Property | Type | Description |
|---|---|---|
DrawInstructions |
Action |
Your drawing code, run every frame inside the view port, over its background and under its children, as described above. |
DeviceBounds |
Rectangle |
Read-only. The view port’s bounds in device pixels, the rectangle GraphicsDevice.Viewport is set to. It can be read outside the draw instructions too, for example for a camera’s aspect ratio. |
MinDepth |
float |
The minimum depth of the viewport’s depth range. Defaults to DefaultSettings.DefaultMinDepth (0). |
MaxDepth |
float |
The maximum depth of the viewport’s depth range. Defaults to DefaultSettings.DefaultMaxDepth (1). |
ViewPort methods
| Method | Description |
|---|---|
ViewPort(string name = null) |
Creates a view port. The name is used by GetElementByName. |
Style class: ViewPortStyle (MinDepth and MaxDepth, see styles).
Drag and drop
Any element can be dragged with the left mouse button. Its DragType decides what a drag does; the drag members
(DragType, DragTarget, DragAndDropRepresentation, IsDropAllowedPredicate, OnDragAndDropStart, OnDrop,
OnDropDenied) are on the base element.
var card = new Label("card")
{
Text = "Torch",
TextAlignment = TextAlignment.Center,
VerticalTextAlignment = VerticalTextAlignment.Center,
ForegroundColor = new Color(20, 14, 10),
BackgroundColor = new Color(233, 194, 122),
DesiredWidth = 90,
DesiredHeight = 120,
Margin = (16, 24),
HitTest = true,
DragType = DragType.DragAndDrop,
// what follows the mouse: a half transparent picture of the card
DragAndDropRepresentation = new DragAndDropRepresentation
{
UseTargetAppearance = true,
Transparency = 0.4f
}
};
var slot = new Border("slot")
{
Thickness = 2,
ForegroundColor = new Color(168, 131, 74),
BackgroundColor = new Color(26, 20, 15),
DesiredWidth = 98,
DesiredHeight = 128,
Margin = (300, 20),
HitTest = true,
Content = new Label
{
Text = "Slot",
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
}
};
// decides whether the dragged element may land here, and what happens when it does
slot.IsDropAllowedPredicate = dragged => dragged == card;
slot.OnDrop += (dragged, destination) => Console.WriteLine("Dropped in the slot");
slot.OnDropDenied += (dragged, destination) => Console.WriteLine("Not here");
ui.AddElementToRoot(card);
ui.AddElementToRoot(slot);
The drag starts when the left button is pressed on the element and ends when it is released. The element dragged is
its DragTarget, which is the element itself unless you set another one. Both the element you press and the drop
target must take the mouse: a Label doesn’t by default, hence HitTest = true in the snippet.
With DragOnly the dragged element moves with the mouse: every frame, the mouse movement is added to its left and top
margins and taken from its right and bottom margins, so a stretched element keeps its size. A window’s title bar works this way, with the window as its
DragTarget:
titleBar.DragType = DragType.DragOnly;
titleBar.DragTarget = window;
With DragAndDrop the dragged element stays where it is. Its OnDragAndDropStart is raised, and its
DragAndDropRepresentation, if it has one, is shown above everything else and follows
the mouse, keeping the point you grabbed under the cursor. A drag and drop without a representation works the same, with
nothing drawn under the mouse.
While the mouse is over an element, that element’s IsDropAllowedPredicate is asked whether it takes the dragged
element, and the element goes into the DropAllowed or DropDenied state. On release, the element under the mouse
raises OnDrop when the predicate said yes and OnDropDenied otherwise; an element without a predicate denies every
drop. Both handlers get the dragged element and the drop target. Moving the dragged element to its new place is up to
your OnDrop handler. A drag released where nothing takes it, over the empty background, over a disabled element or
outside the window, is denied: the root element raises OnDropDenied.
A part inside a control (a list row, the text of a text box) uses the drag and drop settings of its control when it has none of its own, so pressing on the text of a draggable control drags the control.
DragType
| Value | Meaning |
|---|---|
None |
The element can’t be dragged. The default. |
DragOnly |
Moves the element, or its DragTarget, with the mouse by changing its margins. |
DragAndDrop |
Shows the representation under the mouse and drops the element on the element under the mouse on release. |
DragAndDropRepresentation
The image that follows the mouse during a drag and drop. It is an Image, so it shows its own Source at
its own size, unless UseTargetAppearance makes it a picture of the dragged element. Set it on the element that is
dragged (the DragTarget) through DragAndDropRepresentation; Transparency makes it see-through.
The representation doesn’t take the mouse, and it is aligned to the top left so that its margin places it under the
mouse; the constructor sets HitTest, HorizontalAlignment and VerticalAlignment for this.
DragAndDropRepresentation properties
| Property | Type | Description |
|---|---|---|
UseTargetAppearance |
bool |
Whether each drag takes a picture of the dragged element, at the start of the drag, and shows it at the element’s size instead of Source. The representation owns that picture and disposes it. The picture is drawn into a render target of its own, after which the render targets set before are set back. |
DragAndDropRepresentation methods
| Method | Description |
|---|---|
DragAndDropRepresentation(string name = null) |
Creates a representation that doesn’t take the mouse, aligned to the top left. |
Style class: ImageStyle, as for any image (see styles).