Custom Unity SpriteAtlas control.
Posted: 30 Jan 2025, 19:18
I'm attempting to override Image to provide support for Unity sprite atlases.
The inline usage looks like this:
The backing xaml is mostly empty:
And when I update the sprite the method is:
No matter what I provide for the viewbox I see the entire image. I have confirmed the ImageBrush is working, just that the Viewbox isn't being respected.
What am I missing?
Ah! I figure the mistake is in the assignment of .ImageSource. Not sure how to use the whole ImageBrush.
The inline usage looks like this:
Code: Select all
<local:AtlasImageExt Atlas="WheatAtlas" Region="farm_wheat_01_lvl1" Width="64" Height="64" />Code: Select all
<Image
x:Class="ArchitectOfRuin.AtlasImageExt"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ArchitectOfRuin"
xmlns:noesis="clr-namespace:NoesisGUI">
</Image>Code: Select all
private void UpdateSprite()
{
if (!_spriteAtlas)
return;
if (string.IsNullOrEmpty(Region))
return;
_sprite = _spriteAtlas.GetSprite(Region);
if (!_sprite)
{
Debug.LogError($"Sprite '{Region}' not found in Atlas '{Atlas}'");
return;
}
// Get the sprite texture rect (in pixels).
var spriteRect = _sprite.textureRect;
// var atlasWidth = _sprite.texture.width;
// var atlasHeight = _sprite.texture.height;
// Convert pixel-based rect to normalized UV coordinates.
var x = spriteRect.x;
var y = spriteRect.y;
var width = spriteRect.width;
var height = spriteRect.height;
Source = new ImageBrush
{
ImageSource = new TextureSource(_sprite.texture),
Viewbox = new Rect(x, y, width, height),
ViewboxUnits = BrushMappingMode.Absolute,
TileMode = TileMode.None,
Stretch = Stretch.None
}.ImageSource;
}
What am I missing?
Ah! I figure the mistake is in the assignment of .ImageSource. Not sure how to use the whole ImageBrush.