In the image above, the first image is loaded via C# script. The second is assigned via the inspector in Unity editor. Note the dark gray border around the first image. How can I load the image via C# and have it not have the border?
The source image is a white-on-transparent PNG 512x512 pixels. It's being displayed in an UnityEngine.UI.Image
sized at 30x30 with a red color assigned. The source image is identical (same location on disk) for both examples above.
The code I am using for the first image is as follows;
var texture = new Texture2D(512, 512);
texture.LoadImage(File.ReadAllBytes(Path.Combine(TexturePath, name)));
image.sprite = Sprite.Create(texture, new Rect(0,0, texture.width, texture.height), new Vector2(.5f,.5f), 100);
where image
is the appropriate UnityEngine.UI.Image
.
Note
The advantage of using the code above is that the images do not need to be embedded in the game that unity ends up building. It means these images can be distributed separately from the game. Using Resources.Load
does not cater for this, and I suspect, is the same as assigning the image via the inspector, meaning that unity has already done something to the texture prior to assignment (likely something by the UnityEditor.TextureImporter
)
Update
I investigated the Texture2D
constructor some more and determined that the following code results in the image above, where the edges of the sprite no longer have the grey border, but now appear jagged. (Setting the last parameter to true
retains the grey border).
var texture = new Texture2D(512, 512, TextureFormat.Alpha8, false);
Some googling has me thinking that the issue is mipmap related, and that the Unity Editor may be resolving this on import due to whatever occurs with UnityEditor.TextureImporter.borderMipMap
as seen here. However, the UnityEditor
namespace is not available when building the project.