I Can't Stand UnityEngine.UI.Image Painting the Transparent Parts


Hello. I'm Hirayama from the Technology Department.
UnityEngine.UI.Image, the "normal Image", paints more than it needs to and puts a heavy load on the GPU, so in this article I'll talk about how I tried cutting down the area it paints.
In the first screenshot, the one on the far right is a normal Image, and the left and center ones are what I made this time. The left one uses the vertices contained in the Sprite; there are more vertices, but the area is smaller. The center one has a black frame laid over it with only the face showing; that cutout is done without a mask, by editing the vertices by hand. The second screenshot is the overdraw view, and you can see that the painted area is smaller.
Also, when images are packed into a SpriteAtlas, if you make the packing tight or allow rotation, a normal Image can no longer display them correctly, but this time I've handled that too. It lets you pack them into less space.
Below is a screenshot at runtime.

With a normal Image, garbage shows up. It also can't handle images that are rotated in the atlas, so the picture of the person at the bottom is upside down. The atlas looks like this.

With the tight setting and rotation allowed, textures can be packed into less space.
The sample code is on GitHub in a runnable form, so feel free to take it. It started as something I made for our game Tokyo Prison , which I tidied up, generalized and made more capable for this article, so I think it should hold up in real use, but I may have introduced bugs along the way. Please treat it as just a sample.
The fill area problem
The GPU load from the area being painted is nothing to sneeze at.
On consoles the talk is of 4K (3840x2160), and even among the smartphones and tablets we carry around, devices with resolutions above 1920x1080 have come out in droves. It's fine for expensive high-end devices to have high resolutions; the problem is the cheap ones. The GPUs in 20,000 or 30,000 yen devices are much weaker, yet they may still have a resolution of 1920x1080. They're nowhere near powerful enough. Be especially careful with ones whose chip is a Snapdragon 4XX. I'm sure every company has devices like that in its lineup of test devices.
I think the reasonable countermeasure is to adjust Screen.width/height at startup and lower the resolution to "just enough". In our Tokyo Prison, the standard resolution is 1136x640. But for various reasons you may not be able to lower the image quality of the illustrations. In such cases, there are roughly two options for reducing the fill area.
- Use SpriteRenderer
- Make it work somehow within UnityEngine.UI
As described in an article on the Terasur Blog, if you use SpriteRenderer, it cuts away the transparent areas when drawing without you doing anything. This is the straightforward way. You can adjust the number of vertices too. But it's hard to use when "we're building with UnityEngine.UI and don't want to mix in SpriteRenderer". That was the case with Tokyo Prison too.
The second option is to make it work somehow within UnityEngine.UI. If you inherit from UnityEngine.UI.MaskableGraphic and fill in the vertices yourself, you can make a component that coexists with the normal Image and Text.
Using the Sprite's vertices
The vertex arrays used by SpriteRenderer are held by the Sprite. Using the three properties vertices, uv and triangles, we implement UnityEngine.UI.Graphic.OnPopulateMesh. The code for a minimal component using this looks like the following.
using UnityEngine;
using UnityEngine.UI;
public class MinimumCutoutImage : MaskableGraphic
{
[SerializeField]
Sprite _sprite;
public override Texture mainTexture { get { return (_sprite != null) ? _sprite.texture : null; } }
protected override void OnPopulateMesh(VertexHelper vh)
{
vh.Clear();
if (_sprite == null){ return; }
for (int i = 0; i < _sprite.vertices.Length; i++)
{
vh.AddVert(_sprite.vertices[i] * _sprite.pixelsPerUnit, this.color, _sprite.uv[i]);
}
for (int i = 0; i < _sprite.triangles.Length; i += 3)
{
vh.AddTriangle(_sprite.triangles[i + 0], _sprite.triangles[i + 1], _sprite.triangles[i + 2]);
}
}
}
This is on GitHub too. As with a normal Image, you set the Sprite in the Inspector, and in OnPopulateMesh you set the vertices on the VertexHelper you're given. UnityEngine.UI usually sets sizes and positions in pixels, so Sprite.pixelsPerUnit needs to be multiplied into the vertex coordinates (vertices).
I want it to be compatible with the normal Image
The MinimumCutoutImage shown above is actually quite inconvenient. It will probably be used to replace a normal Image later, so if width and height are the same, you'd want it to be the same size, but it isn't. It currently doesn't look at RectTransform.sizeDelta, so whatever you put in width or height, the size doesn't change. Not having a SetNativeSize button is just as inconvenient. So we need to modify it further.
First, SetNativeSize
First, let's add a SetNativeSize button. We prepare a function that puts the Sprite's resolution into RectTransform.sizeDelta, and provide it as a button in an editor extension.
public class CutoutImage : MaskableGraphic
{
/// ...snip...
public override void SetNativeSize()
{
if (_sprite == null)
{
return;
}
var rect = _sprite.rect;
rectTransform.sizeDelta = new Vector2(
rect.width,
rect.height);
}
#if UNITY_EDITOR
[CustomEditor(typeof(CutoutImage), true)]
public class Inspector : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
var self = (CutoutImage)target;
if (GUILayout.Button("Set Native Size"))
{
self.SetNativeSize();
}
}
}
#endif
}
The Sprite's resolution can be obtained with Sprite.rect. It returns the original resolution even when the sprite is in a SpriteAtlas. You just put its width and height into rectTransform.sizeDelta. And the editor extension button can be added with code like the above. I think it's easiest to define the editor extension class (Inspector above) inside the class, since that gives it easy access to private members.
Now we have a SetNativeSize button, and pressing it sets width and height automatically. Here is the code at this stage.
Size adjustment
We've added the button, but nothing happens when you press it. By default, width and height are 100, but even if you press the button in that state and make it, say, 256x256, the display doesn't change at all. So let's make the display size change according to width and height, like a normal Image.
The vertex coordinates originally in Sprite.vertices are not in pixels. As we already saw, they only become pixels once multiplied by Sprite.pixelsPerUnit. In addition, if you want to scale by adjusting width and height like a normal Image, you need to reflect the values of RectTransform.sizeDelta, which holds width and height, in the vertex coordinates.
For example, if the original resolution is 128x256 and you want to display it at width=64, height=64, x needs to be multiplied by 0.5 and y by 0.25. In other words, you compute the ratio between the original resolution and width and height, and multiply by it.
protected override void OnPopulateMesh(VertexHelper vh)
{
vh.Clear();
if (_sprite == null){ return; }
var spriteRect = _sprite.rect;
var sizeDelta = rectTransform.sizeDelta;
var scale = new Vector2(
_sprite.pixelsPerUnit * sizeDelta.x / spriteRect.width,
_sprite.pixelsPerUnit * sizeDelta.y / spriteRect.height);
for (int i = 0; i < _sprite.vertices.Length; i++)
{
var v = new Vector2(
_sprite.vertices[i].x * scale.x,
_sprite.vertices[i].y * scale.y);
vh.AddVert(v, this.color, _sprite.uv[i]);
}
/// ...snip...
You just multiply each vertex coordinate by the ratio of Sprite.rect to RectTransform.sizeDelta. Now the size is correct. Here is the code at this stage.
The position is off...
Actually, there's still something we need to handle. Changing RectTransform.pivot shifts the position.


In the upper figure, the RectTransform's pivot is (0.5, 0.5) and the white background and the picture of the
person line up, but in the lower figure, the pivot is (0, 0) and it's shifted from the background. With a normal
Image, when you change the pivot, PosX and PosY are adjusted automatically so it stays in the same place, but for
some reason that isn't happening.
In other words, we have to do ourselves what Unity does internally when you change the pivot on a normal Image. Look at the code above. Nowhere does it look at RectTransform.pivot. If PosX and PosY, that is RectTransform.anchoredPosition, change while the pivot is ignored, of course the position shifts.
So let's fix the code to look at RectTransform.pivot. RectTransform.pivot ranges from 0 to 1 and represents a ratio
of width and height. So we just add that much to the vertex coordinates. For example, say that originally, with the
pivot at (0.5, 0.5), it was in the center. If you change the pivot to (0, 0), PosX and PosY automatically change
to -128, so it shifts to the lower left. We just need to compensate for this: "when the pivot decreases, increase
the coordinates by that amount". The result looks like this.
protected override void OnPopulateMesh(VertexHelper vh)
{
vh.Clear();
if (_sprite == null){ return; }
var spriteRect = _sprite.rect;
var sizeDelta = rectTransform.sizeDelta;
var scale = new Vector2(
_sprite.pixelsPerUnit * sizeDelta.x / spriteRect.width,
_sprite.pixelsPerUnit * sizeDelta.y / spriteRect.height);
var offset = new Vector2(
sizeDelta.x * (0.5f - rectTransform.pivot.x),
sizeDelta.y * (0.5f - rectTransform.pivot.y));
for (int i = 0; i < _sprite.vertices.Length; i++)
{
var v = new Vector2(
_sprite.vertices[i].x * scale.x,
_sprite.vertices[i].y * scale.y);
v += offset;
vh.AddVert(v, this.color, _sprite.uv[i]);
}
/// ...snip...
We prepare a Vector2 called offset and add it to every vertex. The smaller the pivot, the larger the value we add,
hence the subtraction 0.5f - rectTransform.pivot.x. We multiply this by width (=sizeDelta.x) and height
(=sizeDelta.y) to convert to pixels.

Happily, it lines up now. Here is the code at this stage.
Actually, there's much more
Please take a quick look at the finished CutoutImage code.
It's quite long, isn't it? The truth is, CutoutImage contains so many modifications that explaining each one in detail step by step like this would get too long. So in this article I'll only give an overview of what else needs doing to reach the finished version.
It doesn't look at the Sprite's pivot
In fact, the Sprite has a pivot too. Did the bare number
0.5f in the code earlier bother anyone? That was actually the Sprite's pivot.

It worked out because the default value happens to be 0.5, but if it had been changed, the position would be off as things stand. So it won't really work correctly unless the code also looks at Sprite.pivot.
A feature for setting vertices by hand
Using the Sprite's vertices as they are is relatively easy, but there are cases where you don't want to use them as they are. That said, if it's simply that "the automatically generated vertices are too many / too few", you can adjust them as described in the manual, so there's no problem.
So what are the cases where you want to edit the vertices by hand? When you'd otherwise want a mask. Look at this.

Only the face is cut out, with a black frame around it. You could do this with a mask, but adding components is a hassle, it needs stencil buffer operations so it's heavy on the GPU, and the shader switches, so DrawCalls increase and the CPU load goes up. Nothing good about it. If you wanted to, you could do it with the "manual sprite vertex adjustment" mentioned above, but the shape of the frame is usually different depending on where it's used. In Tokyo Prison, it's not a neat rectangle like in this example; the shape differs depending on the place, so doing it on the sprite vertex side is even more of a hassle. It's better to be able to do it as a setting on the component.
So the finished version includes a feature for editing vertices by hand.

As with the pivot, you can set vertices by hand in coordinates where the left edge is 0, the right edge 1, the bottom edge 0 and the top edge 1. Enable VertexOverrideEnabled and then edit OverrideVertices. The vertices are interpreted as being in clockwise order. Also, if you enable the "GUI VertexEditing" toggle in the Inspector, a circle appears at each vertex in the Scene view, and you can adjust the vertices by dragging these circles with the mouse.
Implementing this feature is quite a pain, and a large part of CutoutImage's line count is devoted to it.
The most troublesome part is the uv, that is, the texture coordinates. When you make the vertices yourself, you can't use Sprite.uv, so you have to generate them yourself. Sprite.vertices and Sprite.uv can be converted into each other by some linear transformation, so I take three vertices and three uvs, set up simultaneous equations, compute the inverse matrix, and keep the transformation as a 2x3 matrix. The vertices keep changing with the mouse and so on; each time, OnPopulateMesh is called, and in it the uvs are computed by transforming with this matrix.
If rotation was not allowed when generating the SpriteAtlas, and the packing is not tight, the position in the atlas can be found with Sprite.textureRect or Sprite.textureRectOffset, so you only need to shift it (these properties throw exceptions when there's rotation or the packing is tight).
Actually, the implementation used in Tokyo Prison doesn't allow tight packing or rotation, and was much simpler code. While I was at it, I tried supporting them this time, but it's quite a pain. Unity's standard 4x4 matrix library is awkward to use, so I also implemented the functions I needed for 2x3 and 3x3 matrices myself. Purely for fun.
Also, for editing vertices with the mouse, I implemented OnSceneGUI on the editor extension side, and there I draw circles that can be moved with the mouse, using things like Handles.matrix, HandleUtility.GetHandleSize and Handles.FreeMoveHandle.
Gizmo support
By implementing MonoBehaviour.OnDrawGizmosSelected, you can do various things when the object is selected in the editor. Here, I draw a wireframe so you can see what the vertices look like. The code is roughly around here.

I set Transform.localToWorldMatrix on Gizmos.matrix, put whatever color I like into Gizmos.color, and pass the vertex coordinates to Gizmos.DrawLine to draw. Since Gizmos.matrix has been given the matrix that converts from local to world coordinates, the vertices can stay in local coordinates. The local coordinates of a RectTransform are the familiar pixel-based coordinate system, so you can pass exactly what you passed to the VertexHelper in OnPopulateMesh(). In this implementation I keep them in an array to avoid recomputing them.
In closing
This time, starting from the problem of "reducing the fill area", I touched on the specification of Sprite, creating your own class that inherits from UnityEngine.UI.Graphic, generating vertices by hand, and how to implement gizmos.
The key to writing this kind of thing is "coordinate transformation". Being comfortable with expressing transformations, including rotation, scaling and translation, as matrices, and with the relationship between simultaneous equations and matrices, makes all sorts of things easier, so I recommend it.
By the way, the person who originally used gizmos to display various things and made it possible to edit vertices with the mouse is Nakayama, who wrote this article. Until he implemented it, it had never occurred to me to display gizmos myself, and I was editing vertex coordinates by fiddling with numbers while thinking "what a pain". When you spend every day hounded by tasks and bugs, you lose the slack to look into even little things, which isn't good. I'd like to always have enough slack to balance the short term and the long term.