rds1983 / StbSharp

C# port of the famous C framework
69 stars 8 forks source link

在unity中 #4

Open aliveanyang opened 6 years ago

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

        UnityEngine.Texture2D texture2D = new UnityEngine.Texture2D(Image.Width, Image.Height);
        texture2D.SetPixels32(ToColors(Image.Data));
        texture2D.Apply();
        有什么解决方法吗?
rds1983 commented 6 years ago

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);
        }