我在Visual Studio WindowsFormsApplication中的一些简单代码中创建了一个位图像素图像。我想把这个图像放到我的Unity游戏中,现在替换我加载到游戏中的股票图像。如何编写Unity代码脚本以使用此图像?最好是,我不想将我的像素图像保存在桌面上,而是将其直接加载到我的Unity游戏中。
答案 0 :(得分:0)
好的,拍摄图像,将其编码为byte
数组
来自:https://msdn.microsoft.com/en-us/library/aa970062(v=vs.110).aspx
int width = 128;
int height = 128;
int stride = width;
byte[] pixels = new byte[height * stride];
// Define the image palette
BitmapPalette myPalette = BitmapPalettes.Halftone256;
// Creates a new empty image with the pre-defined palette
BitmapSource image = BitmapSource.Create(
width,
height,
96,
96,
PixelFormats.Indexed8,
myPalette,
pixels,
stride);
FileStream stream = new FileStream("new.png", FileMode.Create);
PngBitmapEncoder encoder = new PngBitmapEncoder();
TextBlock myTextBlock = new TextBlock();
myTextBlock.Text = "Codec Author is: " + encoder.CodecInfo.Author.ToString();
encoder.Interlace = PngInterlaceOption.On;
encoder.Frames.Add(BitmapFrame.Create(image));
encoder.Save(stream);
然后让它通过套接字连接或公共文件位置发送它,并将其加载到LoadImage
来自:https://docs.unity3d.com/ScriptReference/Texture2D.LoadImage.html
public class ExampleClass : MonoBehaviour {
// Load a .jpg or .png file by adding .bytes extensions to the file
// and dragging it on the imageAsset variable.
public TextAsset imageAsset;
public void Start() {
// Create a texture. Texture size does not matter, since
// LoadImage will replace with with incoming image size.
Texture2D tex = new Texture2D(2, 2);
tex.LoadImage(imageAsset.bytes);
GetComponent<Renderer>().material.mainTexture = tex;
}
}