我想从图像文件中获取数据并以Unity可以读取的纹理显示该信息。
我能够将像素信息放入字节数组中,但是屏幕上什么也没有显示。我实际上如何显示图像?
pcxFile = File.ReadAllBytes("Assets/5_ImageParser/bagit_icon.pcx");
int startPoint = 128;
int height = 152;
int width = 152;
target = new Texture2D(height, width);
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
timesDone ++;
pixels[x, y] = new Color(pcxFile[startPoint], pcxFile[startPoint+1], pcxFile[startPoint+2]);
startPoint += 4;
target.SetPixel(x, y, pixels[x, y]);
}
}
target.Apply();
target.EncodeToJPG();
答案 0 :(得分:2)
好吧,(假设您正确地获得了像素数据)您必须将创建纹理的东西分配给某些东西...
我会使用例如RawImage,因为它不需要Sprite
(就像UI.Image
组件那样-也请参见RawImage Manual):
// Reference this in the Inspector
public RawImage image;
//...
pcxFile = File.ReadAllBytes("Assets/5_ImageParser/bagit_icon.pcx");
int startPoint = 128;
int height = 152;
int width = 152;
target = new Texture2D(height, width);
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
timesDone ++;
pixels[x, y] = new Color(pcxFile[startPoint], pcxFile[startPoint+1], pcxFile[startPoint+2]);
startPoint += 4;
target.SetPixel(x, y, pixels[x, y]);
}
}
target.Apply();
// You don't need this. Only if you are also going to save it locally
// as an actual *.jpg file or if you are going to
// e.g. upload it later via http POST
//
// In this case however you would have to asign the result
// to a variable in order to use it later
//var rawJpgBytes = target.EncodeToJPG();
// Assign the texture to the RawImage component
image.texture = target;
或者与常规Image
组件一起使用,使用Sprite.Create
从纹理中创建一个Sprite
:
// Reference this in the Inspector
public Image image;
// ...
var sprite = Sprite.Create(target, new Rect(0.0f, 0.0f, target.width, target.height), new Vector2(0.5f, 0.5f), 100.0f);
image.sprite = sprite;
提示1
为了获得正确的纵横比,我通常使用一些技巧:
RectTransform
中设置所需的“最大尺寸” RawImage
/ Image
旁边(在子对象上)添加一个AspectRatioFitter
(另请参见AspectRatioFitter Manual)并将AspectMode
设置为{{ 1}}。现在在代码中调整纵横比(您可以从纹理中获取):
FitInParent
提示2
与重复调用public RawImage image;
public AspectRatioFitter fitter;
//...
image.texture = target;
var ratio = target.width / target.height;
fitter.aspectRatio = ratio;
相比,对所有像素一次调用SetPixels
是“便宜”的事情:
SetPixel
(我不知道您的// ...
startPoint = 0;
pixels = new Color[width * height]();
for(int i = 0; i < pixels.Length; i++)
{
pixels[i] = new Color(pcxFile[startPoint], pcxFile[startPoint+1], pcxFile[startPoint+2]);
startPoint += 4;
}
target.SetPixels(pixels);
target.Apply();
// ...
格式的工作原理如何,但也许您甚至可以使用LoadRawTextureData