Skip to content
This repository has been archived by the owner on Jul 16, 2019. It is now read-only.

在unity中 #4

Open
aliveanyang opened this issue Sep 27, 2018 · 1 comment
Open

在unity中 #4

aliveanyang opened this issue Sep 27, 2018 · 1 comment

Comments

@aliveanyang
Copy link

aliveanyang commented Sep 27, 2018

  你好,我目前正在使用Unity3d,并试图使用StbSharp加载一个纹理,加载后的纹理是FilpY的效果

        UnityEngine.Texture2D texture2D = new UnityEngine.Texture2D(Image.Width, Image.Height);
        texture2D.SetPixels32(ToColors(Image.Data));
        texture2D.Apply();
        有什么解决方法吗?
@aliveanyang aliveanyang changed the title 在unity中这样Y轴是反着 在unity中 Sep 27, 2018
@rds1983
Copy link
Owner

rds1983 commented Sep 27, 2018

Hi,
Sorry, I dont speak Chinese(I've used the google translate to read original question) and will answer in English.
Probably Unity3D expects texture to be flipped vertically.
So you might change ToColors method, so it flips the image along with converting it to Colors[].
I.e. following code worked for me:

		private Color[] ToColors(StbSharp.Image image)
		{
			Color[] colors = new Color[image.Width * image.Height];
			for (int y = 0; y < image.Height; ++y)
			{
				for (int x = 0; x < image.Width; ++x)
				{
					int srcPos = y * image.Width + x;
					int destPos = ((image.Height - y - 1) * image.Width + x) * 4;

					colors[srcPos].r = image.Data[destPos] / 255.0f;
					colors[srcPos].g = image.Data[destPos + 1] / 255.0f;
					colors[srcPos].b = image.Data[destPos + 2] / 255.0f;
					colors[srcPos].a = image.Data[destPos + 3] / 255.0f;
				}
			}

			return colors;
		}

		private void OnGUI()
		{
			if (_texture == null)
			{
				StbSharp.Image image;
				using (var stream = File.OpenRead("d:\\temp\\logo.png"))
				{
					ImageReader reader = new ImageReader();
					image = reader.Read(stream, StbImage.STBI_rgb_alpha);
				}

				Color[] colors = ToColors(image);
				_texture = new Texture2D(image.Width, image.Height);
				_texture.SetPixels(colors);
				_texture.Apply();
			}

			GUI.DrawTexture(new Rect(100, 100, _texture.width, _texture.height), _texture);
		}

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants